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/SourceLocation.h" |
27 | #include "clang/Basic/Stack.h" |
28 | #include "clang/Basic/TargetInfo.h" |
29 | #include "clang/Sema/DeclSpec.h" |
30 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
31 | #include "clang/Sema/Initialization.h" |
32 | #include "clang/Sema/Lookup.h" |
33 | #include "clang/Sema/Overload.h" |
34 | #include "clang/Sema/ParsedTemplate.h" |
35 | #include "clang/Sema/Scope.h" |
36 | #include "clang/Sema/SemaInternal.h" |
37 | #include "clang/Sema/Template.h" |
38 | #include "clang/Sema/TemplateDeduction.h" |
39 | #include "llvm/ADT/SmallBitVector.h" |
40 | #include "llvm/ADT/SmallString.h" |
41 | #include "llvm/ADT/StringExtras.h" |
42 | |
43 | #include <iterator> |
44 | #include <optional> |
45 | using namespace clang; |
46 | using namespace sema; |
47 | |
48 | // Exported for use by Parser. |
49 | SourceRange |
50 | clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, |
51 | unsigned N) { |
52 | if (!N) return SourceRange(); |
53 | return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); |
54 | } |
55 | |
56 | unsigned Sema::getTemplateDepth(Scope *S) const { |
57 | unsigned Depth = 0; |
58 | |
59 | // Each template parameter scope represents one level of template parameter |
60 | // depth. |
61 | for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope; |
62 | TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) { |
63 | ++Depth; |
64 | } |
65 | |
66 | // Note that there are template parameters with the given depth. |
67 | auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); }; |
68 | |
69 | // Look for parameters of an enclosing generic lambda. We don't create a |
70 | // template parameter scope for these. |
71 | for (FunctionScopeInfo *FSI : getFunctionScopes()) { |
72 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) { |
73 | if (!LSI->TemplateParams.empty()) { |
74 | ParamsAtDepth(LSI->AutoTemplateParameterDepth); |
75 | break; |
76 | } |
77 | if (LSI->GLTemplateParameterList) { |
78 | ParamsAtDepth(LSI->GLTemplateParameterList->getDepth()); |
79 | break; |
80 | } |
81 | } |
82 | } |
83 | |
84 | // Look for parameters of an enclosing terse function template. We don't |
85 | // create a template parameter scope for these either. |
86 | for (const InventedTemplateParameterInfo &Info : |
87 | getInventedParameterInfos()) { |
88 | if (!Info.TemplateParams.empty()) { |
89 | ParamsAtDepth(Info.AutoTemplateParameterDepth); |
90 | break; |
91 | } |
92 | } |
93 | |
94 | return Depth; |
95 | } |
96 | |
97 | /// \brief Determine whether the declaration found is acceptable as the name |
98 | /// of a template and, if so, return that template declaration. Otherwise, |
99 | /// returns null. |
100 | /// |
101 | /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent |
102 | /// is true. In all other cases it will return a TemplateDecl (or null). |
103 | NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D, |
104 | bool AllowFunctionTemplates, |
105 | bool AllowDependent) { |
106 | D = D->getUnderlyingDecl(); |
107 | |
108 | if (isa<TemplateDecl>(Val: D)) { |
109 | if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D)) |
110 | return nullptr; |
111 | |
112 | return D; |
113 | } |
114 | |
115 | if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
116 | // C++ [temp.local]p1: |
117 | // Like normal (non-template) classes, class templates have an |
118 | // injected-class-name (Clause 9). The injected-class-name |
119 | // can be used with or without a template-argument-list. When |
120 | // it is used without a template-argument-list, it is |
121 | // equivalent to the injected-class-name followed by the |
122 | // template-parameters of the class template enclosed in |
123 | // <>. When it is used with a template-argument-list, it |
124 | // refers to the specified class template specialization, |
125 | // which could be the current specialization or another |
126 | // specialization. |
127 | if (Record->isInjectedClassName()) { |
128 | Record = cast<CXXRecordDecl>(Record->getDeclContext()); |
129 | if (Record->getDescribedClassTemplate()) |
130 | return Record->getDescribedClassTemplate(); |
131 | |
132 | if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) |
133 | return Spec->getSpecializedTemplate(); |
134 | } |
135 | |
136 | return nullptr; |
137 | } |
138 | |
139 | // 'using Dependent::foo;' can resolve to a template name. |
140 | // 'using typename Dependent::foo;' cannot (not even if 'foo' is an |
141 | // injected-class-name). |
142 | if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D)) |
143 | return D; |
144 | |
145 | return nullptr; |
146 | } |
147 | |
148 | void Sema::FilterAcceptableTemplateNames(LookupResult &R, |
149 | bool AllowFunctionTemplates, |
150 | bool AllowDependent) { |
151 | LookupResult::Filter filter = R.makeFilter(); |
152 | while (filter.hasNext()) { |
153 | NamedDecl *Orig = filter.next(); |
154 | if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent)) |
155 | filter.erase(); |
156 | } |
157 | filter.done(); |
158 | } |
159 | |
160 | bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, |
161 | bool AllowFunctionTemplates, |
162 | bool AllowDependent, |
163 | bool AllowNonTemplateFunctions) { |
164 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { |
165 | if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent)) |
166 | return true; |
167 | if (AllowNonTemplateFunctions && |
168 | isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl())) |
169 | return true; |
170 | } |
171 | |
172 | return false; |
173 | } |
174 | |
175 | TemplateNameKind Sema::isTemplateName(Scope *S, |
176 | CXXScopeSpec &SS, |
177 | bool hasTemplateKeyword, |
178 | const UnqualifiedId &Name, |
179 | ParsedType ObjectTypePtr, |
180 | bool EnteringContext, |
181 | TemplateTy &TemplateResult, |
182 | bool &MemberOfUnknownSpecialization, |
183 | bool Disambiguation) { |
184 | assert(getLangOpts().CPlusPlus && "No template names in C!" ); |
185 | |
186 | DeclarationName TName; |
187 | MemberOfUnknownSpecialization = false; |
188 | |
189 | switch (Name.getKind()) { |
190 | case UnqualifiedIdKind::IK_Identifier: |
191 | TName = DeclarationName(Name.Identifier); |
192 | break; |
193 | |
194 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
195 | TName = Context.DeclarationNames.getCXXOperatorName( |
196 | Op: Name.OperatorFunctionId.Operator); |
197 | break; |
198 | |
199 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
200 | TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier); |
201 | break; |
202 | |
203 | default: |
204 | return TNK_Non_template; |
205 | } |
206 | |
207 | QualType ObjectType = ObjectTypePtr.get(); |
208 | |
209 | AssumedTemplateKind AssumedTemplate; |
210 | LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName); |
211 | if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext, |
212 | MemberOfUnknownSpecialization, RequiredTemplate: SourceLocation(), |
213 | ATK: &AssumedTemplate, |
214 | /*AllowTypoCorrection=*/!Disambiguation)) |
215 | return TNK_Non_template; |
216 | |
217 | if (AssumedTemplate != AssumedTemplateKind::None) { |
218 | TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName)); |
219 | // Let the parser know whether we found nothing or found functions; if we |
220 | // found nothing, we want to more carefully check whether this is actually |
221 | // a function template name versus some other kind of undeclared identifier. |
222 | return AssumedTemplate == AssumedTemplateKind::FoundNothing |
223 | ? TNK_Undeclared_template |
224 | : TNK_Function_template; |
225 | } |
226 | |
227 | if (R.empty()) |
228 | return TNK_Non_template; |
229 | |
230 | NamedDecl *D = nullptr; |
231 | UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin()); |
232 | if (R.isAmbiguous()) { |
233 | // If we got an ambiguity involving a non-function template, treat this |
234 | // as a template name, and pick an arbitrary template for error recovery. |
235 | bool AnyFunctionTemplates = false; |
236 | for (NamedDecl *FoundD : R) { |
237 | if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) { |
238 | if (isa<FunctionTemplateDecl>(Val: FoundTemplate)) |
239 | AnyFunctionTemplates = true; |
240 | else { |
241 | D = FoundTemplate; |
242 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD); |
243 | break; |
244 | } |
245 | } |
246 | } |
247 | |
248 | // If we didn't find any templates at all, this isn't a template name. |
249 | // Leave the ambiguity for a later lookup to diagnose. |
250 | if (!D && !AnyFunctionTemplates) { |
251 | R.suppressDiagnostics(); |
252 | return TNK_Non_template; |
253 | } |
254 | |
255 | // If the only templates were function templates, filter out the rest. |
256 | // We'll diagnose the ambiguity later. |
257 | if (!D) |
258 | FilterAcceptableTemplateNames(R); |
259 | } |
260 | |
261 | // At this point, we have either picked a single template name declaration D |
262 | // or we have a non-empty set of results R containing either one template name |
263 | // declaration or a set of function templates. |
264 | |
265 | TemplateName Template; |
266 | TemplateNameKind TemplateKind; |
267 | |
268 | unsigned ResultCount = R.end() - R.begin(); |
269 | if (!D && ResultCount > 1) { |
270 | // We assume that we'll preserve the qualifier from a function |
271 | // template name in other ways. |
272 | Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end()); |
273 | TemplateKind = TNK_Function_template; |
274 | |
275 | // We'll do this lookup again later. |
276 | R.suppressDiagnostics(); |
277 | } else { |
278 | if (!D) { |
279 | D = getAsTemplateNameDecl(D: *R.begin()); |
280 | assert(D && "unambiguous result is not a template name" ); |
281 | } |
282 | |
283 | if (isa<UnresolvedUsingValueDecl>(Val: D)) { |
284 | // We don't yet know whether this is a template-name or not. |
285 | MemberOfUnknownSpecialization = true; |
286 | return TNK_Non_template; |
287 | } |
288 | |
289 | TemplateDecl *TD = cast<TemplateDecl>(Val: D); |
290 | Template = |
291 | FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); |
292 | assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); |
293 | if (SS.isSet() && !SS.isInvalid()) { |
294 | NestedNameSpecifier *Qualifier = SS.getScopeRep(); |
295 | Template = Context.getQualifiedTemplateName(NNS: Qualifier, TemplateKeyword: hasTemplateKeyword, |
296 | Template); |
297 | } |
298 | |
299 | if (isa<FunctionTemplateDecl>(Val: TD)) { |
300 | TemplateKind = TNK_Function_template; |
301 | |
302 | // We'll do this lookup again later. |
303 | R.suppressDiagnostics(); |
304 | } else { |
305 | assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || |
306 | isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || |
307 | isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)); |
308 | TemplateKind = |
309 | isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template : |
310 | isa<ConceptDecl>(Val: TD) ? TNK_Concept_template : |
311 | TNK_Type_template; |
312 | } |
313 | } |
314 | |
315 | TemplateResult = TemplateTy::make(P: Template); |
316 | return TemplateKind; |
317 | } |
318 | |
319 | bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name, |
320 | SourceLocation NameLoc, CXXScopeSpec &SS, |
321 | ParsedTemplateTy *Template /*=nullptr*/) { |
322 | bool MemberOfUnknownSpecialization = false; |
323 | |
324 | // We could use redeclaration lookup here, but we don't need to: the |
325 | // syntactic form of a deduction guide is enough to identify it even |
326 | // if we can't look up the template name at all. |
327 | LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName); |
328 | if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(), |
329 | /*EnteringContext*/ false, |
330 | MemberOfUnknownSpecialization)) |
331 | return false; |
332 | |
333 | if (R.empty()) return false; |
334 | if (R.isAmbiguous()) { |
335 | // FIXME: Diagnose an ambiguity if we find at least one template. |
336 | R.suppressDiagnostics(); |
337 | return false; |
338 | } |
339 | |
340 | // We only treat template-names that name type templates as valid deduction |
341 | // guide names. |
342 | TemplateDecl *TD = R.getAsSingle<TemplateDecl>(); |
343 | if (!TD || !getAsTypeTemplateDecl(TD)) |
344 | return false; |
345 | |
346 | if (Template) |
347 | *Template = TemplateTy::make(P: TemplateName(TD)); |
348 | return true; |
349 | } |
350 | |
351 | bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, |
352 | SourceLocation IILoc, |
353 | Scope *S, |
354 | const CXXScopeSpec *SS, |
355 | TemplateTy &SuggestedTemplate, |
356 | TemplateNameKind &SuggestedKind) { |
357 | // We can't recover unless there's a dependent scope specifier preceding the |
358 | // template name. |
359 | // FIXME: Typo correction? |
360 | if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) || |
361 | computeDeclContext(SS: *SS)) |
362 | return false; |
363 | |
364 | // The code is missing a 'template' keyword prior to the dependent template |
365 | // name. |
366 | NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); |
367 | Diag(IILoc, diag::err_template_kw_missing) |
368 | << Qualifier << II.getName() |
369 | << FixItHint::CreateInsertion(IILoc, "template " ); |
370 | SuggestedTemplate |
371 | = TemplateTy::make(P: Context.getDependentTemplateName(NNS: Qualifier, Name: &II)); |
372 | SuggestedKind = TNK_Dependent_template_name; |
373 | return true; |
374 | } |
375 | |
376 | bool Sema::LookupTemplateName(LookupResult &Found, |
377 | Scope *S, CXXScopeSpec &SS, |
378 | QualType ObjectType, |
379 | bool EnteringContext, |
380 | bool &MemberOfUnknownSpecialization, |
381 | RequiredTemplateKind RequiredTemplate, |
382 | AssumedTemplateKind *ATK, |
383 | bool AllowTypoCorrection) { |
384 | if (ATK) |
385 | *ATK = AssumedTemplateKind::None; |
386 | |
387 | if (SS.isInvalid()) |
388 | return true; |
389 | |
390 | Found.setTemplateNameLookup(true); |
391 | |
392 | // Determine where to perform name lookup |
393 | MemberOfUnknownSpecialization = false; |
394 | DeclContext *LookupCtx = nullptr; |
395 | bool IsDependent = false; |
396 | if (!ObjectType.isNull()) { |
397 | // This nested-name-specifier occurs in a member access expression, e.g., |
398 | // x->B::f, and we are looking into the type of the object. |
399 | assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist" ); |
400 | LookupCtx = computeDeclContext(T: ObjectType); |
401 | IsDependent = !LookupCtx && ObjectType->isDependentType(); |
402 | assert((IsDependent || !ObjectType->isIncompleteType() || |
403 | !ObjectType->getAs<TagType>() || |
404 | ObjectType->castAs<TagType>()->isBeingDefined()) && |
405 | "Caller should have completed object type" ); |
406 | |
407 | // Template names cannot appear inside an Objective-C class or object type |
408 | // or a vector type. |
409 | // |
410 | // FIXME: This is wrong. For example: |
411 | // |
412 | // template<typename T> using Vec = T __attribute__((ext_vector_type(4))); |
413 | // Vec<int> vi; |
414 | // vi.Vec<int>::~Vec<int>(); |
415 | // |
416 | // ... should be accepted but we will not treat 'Vec' as a template name |
417 | // here. The right thing to do would be to check if the name is a valid |
418 | // vector component name, and look up a template name if not. And similarly |
419 | // for lookups into Objective-C class and object types, where the same |
420 | // problem can arise. |
421 | if (ObjectType->isObjCObjectOrInterfaceType() || |
422 | ObjectType->isVectorType()) { |
423 | Found.clear(); |
424 | return false; |
425 | } |
426 | } else if (SS.isNotEmpty()) { |
427 | // This nested-name-specifier occurs after another nested-name-specifier, |
428 | // so long into the context associated with the prior nested-name-specifier. |
429 | LookupCtx = computeDeclContext(SS, EnteringContext); |
430 | IsDependent = !LookupCtx && isDependentScopeSpecifier(SS); |
431 | |
432 | // The declaration context must be complete. |
433 | if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx)) |
434 | return true; |
435 | } |
436 | |
437 | bool ObjectTypeSearchedInScope = false; |
438 | bool AllowFunctionTemplatesInLookup = true; |
439 | if (LookupCtx) { |
440 | // Perform "qualified" name lookup into the declaration context we |
441 | // computed, which is either the type of the base of a member access |
442 | // expression or the declaration context associated with a prior |
443 | // nested-name-specifier. |
444 | LookupQualifiedName(R&: Found, LookupCtx); |
445 | |
446 | // FIXME: The C++ standard does not clearly specify what happens in the |
447 | // case where the object type is dependent, and implementations vary. In |
448 | // Clang, we treat a name after a . or -> as a template-name if lookup |
449 | // finds a non-dependent member or member of the current instantiation that |
450 | // is a type template, or finds no such members and lookup in the context |
451 | // of the postfix-expression finds a type template. In the latter case, the |
452 | // name is nonetheless dependent, and we may resolve it to a member of an |
453 | // unknown specialization when we come to instantiate the template. |
454 | IsDependent |= Found.wasNotFoundInCurrentInstantiation(); |
455 | } |
456 | |
457 | if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) { |
458 | // C++ [basic.lookup.classref]p1: |
459 | // In a class member access expression (5.2.5), if the . or -> token is |
460 | // immediately followed by an identifier followed by a <, the |
461 | // identifier must be looked up to determine whether the < is the |
462 | // beginning of a template argument list (14.2) or a less-than operator. |
463 | // The identifier is first looked up in the class of the object |
464 | // expression. If the identifier is not found, it is then looked up in |
465 | // the context of the entire postfix-expression and shall name a class |
466 | // template. |
467 | if (S) |
468 | LookupName(R&: Found, S); |
469 | |
470 | if (!ObjectType.isNull()) { |
471 | // FIXME: We should filter out all non-type templates here, particularly |
472 | // variable templates and concepts. But the exclusion of alias templates |
473 | // and template template parameters is a wording defect. |
474 | AllowFunctionTemplatesInLookup = false; |
475 | ObjectTypeSearchedInScope = true; |
476 | } |
477 | |
478 | IsDependent |= Found.wasNotFoundInCurrentInstantiation(); |
479 | } |
480 | |
481 | if (Found.isAmbiguous()) |
482 | return false; |
483 | |
484 | if (ATK && SS.isEmpty() && ObjectType.isNull() && |
485 | !RequiredTemplate.hasTemplateKeyword()) { |
486 | // C++2a [temp.names]p2: |
487 | // A name is also considered to refer to a template if it is an |
488 | // unqualified-id followed by a < and name lookup finds either one or more |
489 | // functions or finds nothing. |
490 | // |
491 | // To keep our behavior consistent, we apply the "finds nothing" part in |
492 | // all language modes, and diagnose the empty lookup in ActOnCallExpr if we |
493 | // successfully form a call to an undeclared template-id. |
494 | bool AllFunctions = |
495 | getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) { |
496 | return isa<FunctionDecl>(Val: ND->getUnderlyingDecl()); |
497 | }); |
498 | if (AllFunctions || (Found.empty() && !IsDependent)) { |
499 | // If lookup found any functions, or if this is a name that can only be |
500 | // used for a function, then strongly assume this is a function |
501 | // template-id. |
502 | *ATK = (Found.empty() && Found.getLookupName().isIdentifier()) |
503 | ? AssumedTemplateKind::FoundNothing |
504 | : AssumedTemplateKind::FoundFunctions; |
505 | Found.clear(); |
506 | return false; |
507 | } |
508 | } |
509 | |
510 | if (Found.empty() && !IsDependent && AllowTypoCorrection) { |
511 | // If we did not find any names, and this is not a disambiguation, attempt |
512 | // to correct any typos. |
513 | DeclarationName Name = Found.getLookupName(); |
514 | Found.clear(); |
515 | // Simple filter callback that, for keywords, only accepts the C++ *_cast |
516 | DefaultFilterCCC FilterCCC{}; |
517 | FilterCCC.WantTypeSpecifiers = false; |
518 | FilterCCC.WantExpressionKeywords = false; |
519 | FilterCCC.WantRemainingKeywords = false; |
520 | FilterCCC.WantCXXNamedCasts = true; |
521 | if (TypoCorrection Corrected = |
522 | CorrectTypo(Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, |
523 | SS: &SS, CCC&: FilterCCC, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx)) { |
524 | if (auto *ND = Corrected.getFoundDecl()) |
525 | Found.addDecl(D: ND); |
526 | FilterAcceptableTemplateNames(R&: Found); |
527 | if (Found.isAmbiguous()) { |
528 | Found.clear(); |
529 | } else if (!Found.empty()) { |
530 | Found.setLookupName(Corrected.getCorrection()); |
531 | if (LookupCtx) { |
532 | std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts())); |
533 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
534 | Name.getAsString() == CorrectedStr; |
535 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) |
536 | << Name << LookupCtx << DroppedSpecifier |
537 | << SS.getRange()); |
538 | } else { |
539 | diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); |
540 | } |
541 | } |
542 | } |
543 | } |
544 | |
545 | NamedDecl *ExampleLookupResult = |
546 | Found.empty() ? nullptr : Found.getRepresentativeDecl(); |
547 | FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup); |
548 | if (Found.empty()) { |
549 | if (IsDependent) { |
550 | MemberOfUnknownSpecialization = true; |
551 | return false; |
552 | } |
553 | |
554 | // If a 'template' keyword was used, a lookup that finds only non-template |
555 | // names is an error. |
556 | if (ExampleLookupResult && RequiredTemplate) { |
557 | Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template) |
558 | << Found.getLookupName() << SS.getRange() |
559 | << RequiredTemplate.hasTemplateKeyword() |
560 | << RequiredTemplate.getTemplateKeywordLoc(); |
561 | Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(), |
562 | diag::note_template_kw_refers_to_non_template) |
563 | << Found.getLookupName(); |
564 | return true; |
565 | } |
566 | |
567 | return false; |
568 | } |
569 | |
570 | if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && |
571 | !getLangOpts().CPlusPlus11) { |
572 | // C++03 [basic.lookup.classref]p1: |
573 | // [...] If the lookup in the class of the object expression finds a |
574 | // template, the name is also looked up in the context of the entire |
575 | // postfix-expression and [...] |
576 | // |
577 | // Note: C++11 does not perform this second lookup. |
578 | LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), |
579 | LookupOrdinaryName); |
580 | FoundOuter.setTemplateNameLookup(true); |
581 | LookupName(R&: FoundOuter, S); |
582 | // FIXME: We silently accept an ambiguous lookup here, in violation of |
583 | // [basic.lookup]/1. |
584 | FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false); |
585 | |
586 | NamedDecl *OuterTemplate; |
587 | if (FoundOuter.empty()) { |
588 | // - if the name is not found, the name found in the class of the |
589 | // object expression is used, otherwise |
590 | } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() || |
591 | !(OuterTemplate = |
592 | getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) { |
593 | // - if the name is found in the context of the entire |
594 | // postfix-expression and does not name a class template, the name |
595 | // found in the class of the object expression is used, otherwise |
596 | FoundOuter.clear(); |
597 | } else if (!Found.isSuppressingAmbiguousDiagnostics()) { |
598 | // - if the name found is a class template, it must refer to the same |
599 | // entity as the one found in the class of the object expression, |
600 | // otherwise the program is ill-formed. |
601 | if (!Found.isSingleResult() || |
602 | getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() != |
603 | OuterTemplate->getCanonicalDecl()) { |
604 | Diag(Found.getNameLoc(), |
605 | diag::ext_nested_name_member_ref_lookup_ambiguous) |
606 | << Found.getLookupName() |
607 | << ObjectType; |
608 | Diag(Found.getRepresentativeDecl()->getLocation(), |
609 | diag::note_ambig_member_ref_object_type) |
610 | << ObjectType; |
611 | Diag(FoundOuter.getFoundDecl()->getLocation(), |
612 | diag::note_ambig_member_ref_scope); |
613 | |
614 | // Recover by taking the template that we found in the object |
615 | // expression's type. |
616 | } |
617 | } |
618 | } |
619 | |
620 | return false; |
621 | } |
622 | |
623 | void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, |
624 | SourceLocation Less, |
625 | SourceLocation Greater) { |
626 | if (TemplateName.isInvalid()) |
627 | return; |
628 | |
629 | DeclarationNameInfo NameInfo; |
630 | CXXScopeSpec SS; |
631 | LookupNameKind LookupKind; |
632 | |
633 | DeclContext *LookupCtx = nullptr; |
634 | NamedDecl *Found = nullptr; |
635 | bool MissingTemplateKeyword = false; |
636 | |
637 | // Figure out what name we looked up. |
638 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) { |
639 | NameInfo = DRE->getNameInfo(); |
640 | SS.Adopt(Other: DRE->getQualifierLoc()); |
641 | LookupKind = LookupOrdinaryName; |
642 | Found = DRE->getFoundDecl(); |
643 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) { |
644 | NameInfo = ME->getMemberNameInfo(); |
645 | SS.Adopt(Other: ME->getQualifierLoc()); |
646 | LookupKind = LookupMemberName; |
647 | LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl(); |
648 | Found = ME->getMemberDecl(); |
649 | } else if (auto *DSDRE = |
650 | dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) { |
651 | NameInfo = DSDRE->getNameInfo(); |
652 | SS.Adopt(Other: DSDRE->getQualifierLoc()); |
653 | MissingTemplateKeyword = true; |
654 | } else if (auto *DSME = |
655 | dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) { |
656 | NameInfo = DSME->getMemberNameInfo(); |
657 | SS.Adopt(Other: DSME->getQualifierLoc()); |
658 | MissingTemplateKeyword = true; |
659 | } else { |
660 | llvm_unreachable("unexpected kind of potential template name" ); |
661 | } |
662 | |
663 | // If this is a dependent-scope lookup, diagnose that the 'template' keyword |
664 | // was missing. |
665 | if (MissingTemplateKeyword) { |
666 | Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing) |
667 | << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater); |
668 | return; |
669 | } |
670 | |
671 | // Try to correct the name by looking for templates and C++ named casts. |
672 | struct TemplateCandidateFilter : CorrectionCandidateCallback { |
673 | Sema &S; |
674 | TemplateCandidateFilter(Sema &S) : S(S) { |
675 | WantTypeSpecifiers = false; |
676 | WantExpressionKeywords = false; |
677 | WantRemainingKeywords = false; |
678 | WantCXXNamedCasts = true; |
679 | }; |
680 | bool ValidateCandidate(const TypoCorrection &Candidate) override { |
681 | if (auto *ND = Candidate.getCorrectionDecl()) |
682 | return S.getAsTemplateNameDecl(D: ND); |
683 | return Candidate.isKeyword(); |
684 | } |
685 | |
686 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
687 | return std::make_unique<TemplateCandidateFilter>(args&: *this); |
688 | } |
689 | }; |
690 | |
691 | DeclarationName Name = NameInfo.getName(); |
692 | TemplateCandidateFilter CCC(*this); |
693 | if (TypoCorrection Corrected = CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC, |
694 | Mode: CTK_ErrorRecovery, MemberContext: LookupCtx)) { |
695 | auto *ND = Corrected.getFoundDecl(); |
696 | if (ND) |
697 | ND = getAsTemplateNameDecl(D: ND); |
698 | if (ND || Corrected.isKeyword()) { |
699 | if (LookupCtx) { |
700 | std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts())); |
701 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
702 | Name.getAsString() == CorrectedStr; |
703 | diagnoseTypo(Corrected, |
704 | PDiag(diag::err_non_template_in_member_template_id_suggest) |
705 | << Name << LookupCtx << DroppedSpecifier |
706 | << SS.getRange(), false); |
707 | } else { |
708 | diagnoseTypo(Corrected, |
709 | PDiag(diag::err_non_template_in_template_id_suggest) |
710 | << Name, false); |
711 | } |
712 | if (Found) |
713 | Diag(Found->getLocation(), |
714 | diag::note_non_template_in_template_id_found); |
715 | return; |
716 | } |
717 | } |
718 | |
719 | Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id) |
720 | << Name << SourceRange(Less, Greater); |
721 | if (Found) |
722 | Diag(Found->getLocation(), diag::note_non_template_in_template_id_found); |
723 | } |
724 | |
725 | /// ActOnDependentIdExpression - Handle a dependent id-expression that |
726 | /// was just parsed. This is only possible with an explicit scope |
727 | /// specifier naming a dependent type. |
728 | ExprResult |
729 | Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, |
730 | SourceLocation TemplateKWLoc, |
731 | const DeclarationNameInfo &NameInfo, |
732 | bool isAddressOfOperand, |
733 | const TemplateArgumentListInfo *TemplateArgs) { |
734 | DeclContext *DC = getFunctionLevelDeclContext(); |
735 | |
736 | // C++11 [expr.prim.general]p12: |
737 | // An id-expression that denotes a non-static data member or non-static |
738 | // member function of a class can only be used: |
739 | // (...) |
740 | // - if that id-expression denotes a non-static data member and it |
741 | // appears in an unevaluated operand. |
742 | // |
743 | // If this might be the case, form a DependentScopeDeclRefExpr instead of a |
744 | // CXXDependentScopeMemberExpr. The former can instantiate to either |
745 | // DeclRefExpr or MemberExpr depending on lookup results, while the latter is |
746 | // always a MemberExpr. |
747 | bool MightBeCxx11UnevalField = |
748 | getLangOpts().CPlusPlus11 && isUnevaluatedContext(); |
749 | |
750 | // Check if the nested name specifier is an enum type. |
751 | bool IsEnum = false; |
752 | if (NestedNameSpecifier *NNS = SS.getScopeRep()) |
753 | IsEnum = isa_and_nonnull<EnumType>(Val: NNS->getAsType()); |
754 | |
755 | if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum && |
756 | isa<CXXMethodDecl>(Val: DC) && |
757 | cast<CXXMethodDecl>(Val: DC)->isImplicitObjectMemberFunction()) { |
758 | QualType ThisType = cast<CXXMethodDecl>(Val: DC)->getThisType().getNonReferenceType(); |
759 | |
760 | // Since the 'this' expression is synthesized, we don't need to |
761 | // perform the double-lookup check. |
762 | NamedDecl *FirstQualifierInScope = nullptr; |
763 | |
764 | return CXXDependentScopeMemberExpr::Create( |
765 | Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, |
766 | /*IsArrow=*/!Context.getLangOpts().HLSL, |
767 | /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, |
768 | FirstQualifierFoundInScope: FirstQualifierInScope, MemberNameInfo: NameInfo, TemplateArgs); |
769 | } |
770 | |
771 | return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); |
772 | } |
773 | |
774 | ExprResult |
775 | Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, |
776 | SourceLocation TemplateKWLoc, |
777 | const DeclarationNameInfo &NameInfo, |
778 | const TemplateArgumentListInfo *TemplateArgs) { |
779 | // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc |
780 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
781 | if (!QualifierLoc) |
782 | return ExprError(); |
783 | |
784 | return DependentScopeDeclRefExpr::Create( |
785 | Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs); |
786 | } |
787 | |
788 | |
789 | /// Determine whether we would be unable to instantiate this template (because |
790 | /// it either has no definition, or is in the process of being instantiated). |
791 | bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, |
792 | NamedDecl *Instantiation, |
793 | bool InstantiatedFromMember, |
794 | const NamedDecl *Pattern, |
795 | const NamedDecl *PatternDef, |
796 | TemplateSpecializationKind TSK, |
797 | bool Complain /*= true*/) { |
798 | assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || |
799 | isa<VarDecl>(Instantiation)); |
800 | |
801 | bool IsEntityBeingDefined = false; |
802 | if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef)) |
803 | IsEntityBeingDefined = TD->isBeingDefined(); |
804 | |
805 | if (PatternDef && !IsEntityBeingDefined) { |
806 | NamedDecl *SuggestedDef = nullptr; |
807 | if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef), |
808 | Suggested: &SuggestedDef, |
809 | /*OnlyNeedComplete*/ false)) { |
810 | // If we're allowed to diagnose this and recover, do so. |
811 | bool Recover = Complain && !isSFINAEContext(); |
812 | if (Complain) |
813 | diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef, |
814 | MIK: Sema::MissingImportKind::Definition, Recover); |
815 | return !Recover; |
816 | } |
817 | return false; |
818 | } |
819 | |
820 | if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) |
821 | return true; |
822 | |
823 | QualType InstantiationTy; |
824 | if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation)) |
825 | InstantiationTy = Context.getTypeDeclType(TD); |
826 | if (PatternDef) { |
827 | Diag(PointOfInstantiation, |
828 | diag::err_template_instantiate_within_definition) |
829 | << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation) |
830 | << InstantiationTy; |
831 | // Not much point in noting the template declaration here, since |
832 | // we're lexically inside it. |
833 | Instantiation->setInvalidDecl(); |
834 | } else if (InstantiatedFromMember) { |
835 | if (isa<FunctionDecl>(Val: Instantiation)) { |
836 | Diag(PointOfInstantiation, |
837 | diag::err_explicit_instantiation_undefined_member) |
838 | << /*member function*/ 1 << Instantiation->getDeclName() |
839 | << Instantiation->getDeclContext(); |
840 | Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); |
841 | } else { |
842 | assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!" ); |
843 | Diag(PointOfInstantiation, |
844 | diag::err_implicit_instantiate_member_undefined) |
845 | << InstantiationTy; |
846 | Diag(Pattern->getLocation(), diag::note_member_declared_at); |
847 | } |
848 | } else { |
849 | if (isa<FunctionDecl>(Val: Instantiation)) { |
850 | Diag(PointOfInstantiation, |
851 | diag::err_explicit_instantiation_undefined_func_template) |
852 | << Pattern; |
853 | Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); |
854 | } else if (isa<TagDecl>(Val: Instantiation)) { |
855 | Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) |
856 | << (TSK != TSK_ImplicitInstantiation) |
857 | << InstantiationTy; |
858 | NoteTemplateLocation(Decl: *Pattern); |
859 | } else { |
860 | assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!" ); |
861 | if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) { |
862 | Diag(PointOfInstantiation, |
863 | diag::err_explicit_instantiation_undefined_var_template) |
864 | << Instantiation; |
865 | Instantiation->setInvalidDecl(); |
866 | } else |
867 | Diag(PointOfInstantiation, |
868 | diag::err_explicit_instantiation_undefined_member) |
869 | << /*static data member*/ 2 << Instantiation->getDeclName() |
870 | << Instantiation->getDeclContext(); |
871 | Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); |
872 | } |
873 | } |
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. |
888 | void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { |
889 | assert(PrevDecl->isTemplateParameter() && "Not a template parameter" ); |
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 | const auto *ND = cast<NamedDecl>(Val: PrevDecl); |
899 | Diag(Loc, DiagID: DiagId) << ND->getDeclName(); |
900 | NoteTemplateParameterLocation(Decl: *ND); |
901 | } |
902 | |
903 | /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset |
904 | /// the parameter D to reference the templated declaration and return a pointer |
905 | /// to the template declaration. Otherwise, do nothing to D and return null. |
906 | TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { |
907 | if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) { |
908 | D = Temp->getTemplatedDecl(); |
909 | return Temp; |
910 | } |
911 | return nullptr; |
912 | } |
913 | |
914 | ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( |
915 | SourceLocation EllipsisLoc) const { |
916 | assert(Kind == Template && |
917 | "Only template template arguments can be pack expansions here" ); |
918 | assert(getAsTemplate().get().containsUnexpandedParameterPack() && |
919 | "Template template argument pack expansion without packs" ); |
920 | ParsedTemplateArgument Result(*this); |
921 | Result.EllipsisLoc = EllipsisLoc; |
922 | return Result; |
923 | } |
924 | |
925 | static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, |
926 | const ParsedTemplateArgument &Arg) { |
927 | |
928 | switch (Arg.getKind()) { |
929 | case ParsedTemplateArgument::Type: { |
930 | TypeSourceInfo *DI; |
931 | QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &DI); |
932 | if (!DI) |
933 | DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getLocation()); |
934 | return TemplateArgumentLoc(TemplateArgument(T), DI); |
935 | } |
936 | |
937 | case ParsedTemplateArgument::NonType: { |
938 | Expr *E = static_cast<Expr *>(Arg.getAsExpr()); |
939 | return TemplateArgumentLoc(TemplateArgument(E), E); |
940 | } |
941 | |
942 | case ParsedTemplateArgument::Template: { |
943 | TemplateName Template = Arg.getAsTemplate().get(); |
944 | TemplateArgument TArg; |
945 | if (Arg.getEllipsisLoc().isValid()) |
946 | TArg = TemplateArgument(Template, std::optional<unsigned int>()); |
947 | else |
948 | TArg = Template; |
949 | return TemplateArgumentLoc( |
950 | SemaRef.Context, TArg, |
951 | Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context), |
952 | Arg.getLocation(), Arg.getEllipsisLoc()); |
953 | } |
954 | } |
955 | |
956 | llvm_unreachable("Unhandled parsed template argument" ); |
957 | } |
958 | |
959 | /// Translates template arguments as provided by the parser |
960 | /// into template arguments used by semantic analysis. |
961 | void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, |
962 | TemplateArgumentListInfo &TemplateArgs) { |
963 | for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) |
964 | TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this, |
965 | Arg: TemplateArgsIn[I])); |
966 | } |
967 | |
968 | static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, |
969 | SourceLocation Loc, |
970 | IdentifierInfo *Name) { |
971 | NamedDecl *PrevDecl = SemaRef.LookupSingleName( |
972 | S, Name, Loc, NameKind: Sema::LookupOrdinaryName, Redecl: Sema::ForVisibleRedeclaration); |
973 | if (PrevDecl && PrevDecl->isTemplateParameter()) |
974 | SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); |
975 | } |
976 | |
977 | /// Convert a parsed type into a parsed template argument. This is mostly |
978 | /// trivial, except that we may have parsed a C++17 deduced class template |
979 | /// specialization type, in which case we should form a template template |
980 | /// argument instead of a type template argument. |
981 | ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { |
982 | TypeSourceInfo *TInfo; |
983 | QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo); |
984 | if (T.isNull()) |
985 | return ParsedTemplateArgument(); |
986 | assert(TInfo && "template argument with no location" ); |
987 | |
988 | // If we might have formed a deduced template specialization type, convert |
989 | // it to a template template argument. |
990 | if (getLangOpts().CPlusPlus17) { |
991 | TypeLoc TL = TInfo->getTypeLoc(); |
992 | SourceLocation EllipsisLoc; |
993 | if (auto PET = TL.getAs<PackExpansionTypeLoc>()) { |
994 | EllipsisLoc = PET.getEllipsisLoc(); |
995 | TL = PET.getPatternLoc(); |
996 | } |
997 | |
998 | CXXScopeSpec SS; |
999 | if (auto ET = TL.getAs<ElaboratedTypeLoc>()) { |
1000 | SS.Adopt(Other: ET.getQualifierLoc()); |
1001 | TL = ET.getNamedTypeLoc(); |
1002 | } |
1003 | |
1004 | if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) { |
1005 | TemplateName Name = DTST.getTypePtr()->getTemplateName(); |
1006 | if (SS.isSet()) |
1007 | Name = Context.getQualifiedTemplateName(NNS: SS.getScopeRep(), |
1008 | /*HasTemplateKeyword=*/TemplateKeyword: false, |
1009 | Template: Name); |
1010 | ParsedTemplateArgument Result(SS, TemplateTy::make(P: Name), |
1011 | DTST.getTemplateNameLoc()); |
1012 | if (EllipsisLoc.isValid()) |
1013 | Result = Result.getTemplatePackExpansion(EllipsisLoc); |
1014 | return Result; |
1015 | } |
1016 | } |
1017 | |
1018 | // This is a normal type template argument. Note, if the type template |
1019 | // argument is an injected-class-name for a template, it has a dual nature |
1020 | // and can be used as either a type or a template. We handle that in |
1021 | // convertTypeTemplateArgumentToTemplate. |
1022 | return ParsedTemplateArgument(ParsedTemplateArgument::Type, |
1023 | ParsedType.get().getAsOpaquePtr(), |
1024 | TInfo->getTypeLoc().getBeginLoc()); |
1025 | } |
1026 | |
1027 | /// ActOnTypeParameter - Called when a C++ template type parameter |
1028 | /// (e.g., "typename T") has been parsed. Typename specifies whether |
1029 | /// the keyword "typename" was used to declare the type parameter |
1030 | /// (otherwise, "class" was used), and KeyLoc is the location of the |
1031 | /// "class" or "typename" keyword. ParamName is the name of the |
1032 | /// parameter (NULL indicates an unnamed template parameter) and |
1033 | /// ParamNameLoc is the location of the parameter name (if any). |
1034 | /// If the type parameter has a default argument, it will be added |
1035 | /// later via ActOnTypeParameterDefault. |
1036 | NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename, |
1037 | SourceLocation EllipsisLoc, |
1038 | SourceLocation KeyLoc, |
1039 | IdentifierInfo *ParamName, |
1040 | SourceLocation ParamNameLoc, |
1041 | unsigned Depth, unsigned Position, |
1042 | SourceLocation EqualLoc, |
1043 | ParsedType DefaultArg, |
1044 | bool HasTypeConstraint) { |
1045 | assert(S->isTemplateParamScope() && |
1046 | "Template type parameter not in template parameter scope!" ); |
1047 | |
1048 | bool IsParameterPack = EllipsisLoc.isValid(); |
1049 | TemplateTypeParmDecl *Param |
1050 | = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
1051 | KeyLoc, ParamNameLoc, Depth, Position, |
1052 | ParamName, Typename, IsParameterPack, |
1053 | HasTypeConstraint); |
1054 | Param->setAccess(AS_public); |
1055 | |
1056 | if (Param->isParameterPack()) |
1057 | if (auto *LSI = getEnclosingLambda()) |
1058 | LSI->LocalPacks.push_back(Param); |
1059 | |
1060 | if (ParamName) { |
1061 | maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName); |
1062 | |
1063 | // Add the template parameter into the current scope. |
1064 | S->AddDecl(Param); |
1065 | IdResolver.AddDecl(Param); |
1066 | } |
1067 | |
1068 | // C++0x [temp.param]p9: |
1069 | // A default template-argument may be specified for any kind of |
1070 | // template-parameter that is not a template parameter pack. |
1071 | if (DefaultArg && IsParameterPack) { |
1072 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
1073 | DefaultArg = nullptr; |
1074 | } |
1075 | |
1076 | // Handle the default argument, if provided. |
1077 | if (DefaultArg) { |
1078 | TypeSourceInfo *DefaultTInfo; |
1079 | GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo); |
1080 | |
1081 | assert(DefaultTInfo && "expected source information for type" ); |
1082 | |
1083 | // Check for unexpanded parameter packs. |
1084 | if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo, |
1085 | UPPC: UPPC_DefaultArgument)) |
1086 | return Param; |
1087 | |
1088 | // Check the template argument itself. |
1089 | if (CheckTemplateArgument(Arg: DefaultTInfo)) { |
1090 | Param->setInvalidDecl(); |
1091 | return Param; |
1092 | } |
1093 | |
1094 | Param->setDefaultArgument(DefaultTInfo); |
1095 | } |
1096 | |
1097 | return Param; |
1098 | } |
1099 | |
1100 | /// Convert the parser's template argument list representation into our form. |
1101 | static TemplateArgumentListInfo |
1102 | makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { |
1103 | TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, |
1104 | TemplateId.RAngleLoc); |
1105 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), |
1106 | TemplateId.NumArgs); |
1107 | S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs); |
1108 | return TemplateArgs; |
1109 | } |
1110 | |
1111 | bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) { |
1112 | |
1113 | TemplateName TN = TypeConstr->Template.get(); |
1114 | ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl()); |
1115 | |
1116 | // C++2a [temp.param]p4: |
1117 | // [...] The concept designated by a type-constraint shall be a type |
1118 | // concept ([temp.concept]). |
1119 | if (!CD->isTypeConcept()) { |
1120 | Diag(TypeConstr->TemplateNameLoc, |
1121 | diag::err_type_constraint_non_type_concept); |
1122 | return true; |
1123 | } |
1124 | |
1125 | bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid(); |
1126 | |
1127 | if (!WereArgsSpecified && |
1128 | CD->getTemplateParameters()->getMinRequiredArguments() > 1) { |
1129 | Diag(TypeConstr->TemplateNameLoc, |
1130 | diag::err_type_constraint_missing_arguments) |
1131 | << CD; |
1132 | return true; |
1133 | } |
1134 | return false; |
1135 | } |
1136 | |
1137 | bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS, |
1138 | TemplateIdAnnotation *TypeConstr, |
1139 | TemplateTypeParmDecl *ConstrainedParameter, |
1140 | SourceLocation EllipsisLoc) { |
1141 | return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc, |
1142 | AllowUnexpandedPack: false); |
1143 | } |
1144 | |
1145 | bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS, |
1146 | TemplateIdAnnotation *TypeConstr, |
1147 | TemplateTypeParmDecl *ConstrainedParameter, |
1148 | SourceLocation EllipsisLoc, |
1149 | bool AllowUnexpandedPack) { |
1150 | |
1151 | if (CheckTypeConstraint(TypeConstr)) |
1152 | return true; |
1153 | |
1154 | TemplateName TN = TypeConstr->Template.get(); |
1155 | ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl()); |
1156 | |
1157 | DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name), |
1158 | TypeConstr->TemplateNameLoc); |
1159 | |
1160 | TemplateArgumentListInfo TemplateArgs; |
1161 | if (TypeConstr->LAngleLoc.isValid()) { |
1162 | TemplateArgs = |
1163 | makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr); |
1164 | |
1165 | if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) { |
1166 | for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) { |
1167 | if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint)) |
1168 | return true; |
1169 | } |
1170 | } |
1171 | } |
1172 | return AttachTypeConstraint( |
1173 | NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(), |
1174 | NameInfo: ConceptName, NamedConcept: CD, |
1175 | TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr, |
1176 | ConstrainedParameter, EllipsisLoc); |
1177 | } |
1178 | |
1179 | template<typename ArgumentLocAppender> |
1180 | static ExprResult formImmediatelyDeclaredConstraint( |
1181 | Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, |
1182 | ConceptDecl *NamedConcept, SourceLocation LAngleLoc, |
1183 | SourceLocation RAngleLoc, QualType ConstrainedType, |
1184 | SourceLocation ParamNameLoc, ArgumentLocAppender Appender, |
1185 | SourceLocation EllipsisLoc) { |
1186 | |
1187 | TemplateArgumentListInfo ConstraintArgs; |
1188 | ConstraintArgs.addArgument( |
1189 | Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType), |
1190 | /*NTTPType=*/QualType(), Loc: ParamNameLoc)); |
1191 | |
1192 | ConstraintArgs.setRAngleLoc(RAngleLoc); |
1193 | ConstraintArgs.setLAngleLoc(LAngleLoc); |
1194 | Appender(ConstraintArgs); |
1195 | |
1196 | // C++2a [temp.param]p4: |
1197 | // [...] This constraint-expression E is called the immediately-declared |
1198 | // constraint of T. [...] |
1199 | CXXScopeSpec SS; |
1200 | SS.Adopt(Other: NS); |
1201 | ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId( |
1202 | SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo, |
1203 | /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs); |
1204 | if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid()) |
1205 | return ImmediatelyDeclaredConstraint; |
1206 | |
1207 | // C++2a [temp.param]p4: |
1208 | // [...] If T is not a pack, then E is E', otherwise E is (E' && ...). |
1209 | // |
1210 | // We have the following case: |
1211 | // |
1212 | // template<typename T> concept C1 = true; |
1213 | // template<C1... T> struct s1; |
1214 | // |
1215 | // The constraint: (C1<T> && ...) |
1216 | // |
1217 | // Note that the type of C1<T> is known to be 'bool', so we don't need to do |
1218 | // any unqualified lookups for 'operator&&' here. |
1219 | return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr, |
1220 | /*LParenLoc=*/SourceLocation(), |
1221 | LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd, |
1222 | EllipsisLoc, /*RHS=*/nullptr, |
1223 | /*RParenLoc=*/SourceLocation(), |
1224 | /*NumExpansions=*/std::nullopt); |
1225 | } |
1226 | |
1227 | /// Attach a type-constraint to a template parameter. |
1228 | /// \returns true if an error occurred. This can happen if the |
1229 | /// immediately-declared constraint could not be formed (e.g. incorrect number |
1230 | /// of arguments for the named concept). |
1231 | bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS, |
1232 | DeclarationNameInfo NameInfo, |
1233 | ConceptDecl *NamedConcept, |
1234 | const TemplateArgumentListInfo *TemplateArgs, |
1235 | TemplateTypeParmDecl *ConstrainedParameter, |
1236 | SourceLocation EllipsisLoc) { |
1237 | // C++2a [temp.param]p4: |
1238 | // [...] If Q is of the form C<A1, ..., An>, then let E' be |
1239 | // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...] |
1240 | const ASTTemplateArgumentListInfo *ArgsAsWritten = |
1241 | TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context, |
1242 | List: *TemplateArgs) : nullptr; |
1243 | |
1244 | QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0); |
1245 | |
1246 | ExprResult ImmediatelyDeclaredConstraint = |
1247 | formImmediatelyDeclaredConstraint( |
1248 | *this, NS, NameInfo, NamedConcept, |
1249 | TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(), |
1250 | TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(), |
1251 | ParamAsArgument, ConstrainedParameter->getLocation(), |
1252 | [&] (TemplateArgumentListInfo &ConstraintArgs) { |
1253 | if (TemplateArgs) |
1254 | for (const auto &ArgLoc : TemplateArgs->arguments()) |
1255 | ConstraintArgs.addArgument(Loc: ArgLoc); |
1256 | }, EllipsisLoc); |
1257 | if (ImmediatelyDeclaredConstraint.isInvalid()) |
1258 | return true; |
1259 | |
1260 | auto *CL = ConceptReference::Create(Context, /*NNS=*/NS, |
1261 | /*TemplateKWLoc=*/SourceLocation{}, |
1262 | /*ConceptNameInfo=*/NameInfo, |
1263 | /*FoundDecl=*/NamedConcept, |
1264 | /*NamedConcept=*/NamedConcept, |
1265 | /*ArgsWritten=*/ArgsAsWritten); |
1266 | ConstrainedParameter->setTypeConstraint(CR: CL, |
1267 | ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get()); |
1268 | return false; |
1269 | } |
1270 | |
1271 | bool Sema::AttachTypeConstraint(AutoTypeLoc TL, |
1272 | NonTypeTemplateParmDecl *NewConstrainedParm, |
1273 | NonTypeTemplateParmDecl *OrigConstrainedParm, |
1274 | SourceLocation EllipsisLoc) { |
1275 | if (NewConstrainedParm->getType() != TL.getType() || |
1276 | TL.getAutoKeyword() != AutoTypeKeyword::Auto) { |
1277 | Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), |
1278 | diag::err_unsupported_placeholder_constraint) |
1279 | << NewConstrainedParm->getTypeSourceInfo() |
1280 | ->getTypeLoc() |
1281 | .getSourceRange(); |
1282 | return true; |
1283 | } |
1284 | // FIXME: Concepts: This should be the type of the placeholder, but this is |
1285 | // unclear in the wording right now. |
1286 | DeclRefExpr *Ref = |
1287 | BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(), |
1288 | VK_PRValue, OrigConstrainedParm->getLocation()); |
1289 | if (!Ref) |
1290 | return true; |
1291 | ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint( |
1292 | *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(), |
1293 | TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(), |
1294 | BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(), |
1295 | [&](TemplateArgumentListInfo &ConstraintArgs) { |
1296 | for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I) |
1297 | ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I)); |
1298 | }, |
1299 | EllipsisLoc); |
1300 | if (ImmediatelyDeclaredConstraint.isInvalid() || |
1301 | !ImmediatelyDeclaredConstraint.isUsable()) |
1302 | return true; |
1303 | |
1304 | NewConstrainedParm->setPlaceholderTypeConstraint( |
1305 | ImmediatelyDeclaredConstraint.get()); |
1306 | return false; |
1307 | } |
1308 | |
1309 | /// Check that the type of a non-type template parameter is |
1310 | /// well-formed. |
1311 | /// |
1312 | /// \returns the (possibly-promoted) parameter type if valid; |
1313 | /// otherwise, produces a diagnostic and returns a NULL type. |
1314 | QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, |
1315 | SourceLocation Loc) { |
1316 | if (TSI->getType()->isUndeducedType()) { |
1317 | // C++17 [temp.dep.expr]p3: |
1318 | // An id-expression is type-dependent if it contains |
1319 | // - an identifier associated by name lookup with a non-type |
1320 | // template-parameter declared with a type that contains a |
1321 | // placeholder type (7.1.7.4), |
1322 | TSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI); |
1323 | } |
1324 | |
1325 | return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc); |
1326 | } |
1327 | |
1328 | /// Require the given type to be a structural type, and diagnose if it is not. |
1329 | /// |
1330 | /// \return \c true if an error was produced. |
1331 | bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) { |
1332 | if (T->isDependentType()) |
1333 | return false; |
1334 | |
1335 | if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete)) |
1336 | return true; |
1337 | |
1338 | if (T->isStructuralType()) |
1339 | return false; |
1340 | |
1341 | // Structural types are required to be object types or lvalue references. |
1342 | if (T->isRValueReferenceType()) { |
1343 | Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T; |
1344 | return true; |
1345 | } |
1346 | |
1347 | // Don't mention structural types in our diagnostic prior to C++20. Also, |
1348 | // there's not much more we can say about non-scalar non-class types -- |
1349 | // because we can't see functions or arrays here, those can only be language |
1350 | // extensions. |
1351 | if (!getLangOpts().CPlusPlus20 || |
1352 | (!T->isScalarType() && !T->isRecordType())) { |
1353 | Diag(Loc, diag::err_template_nontype_parm_bad_type) << T; |
1354 | return true; |
1355 | } |
1356 | |
1357 | // Structural types are required to be literal types. |
1358 | if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal)) |
1359 | return true; |
1360 | |
1361 | Diag(Loc, diag::err_template_nontype_parm_not_structural) << T; |
1362 | |
1363 | // Drill down into the reason why the class is non-structural. |
1364 | while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { |
1365 | // All members are required to be public and non-mutable, and can't be of |
1366 | // rvalue reference type. Check these conditions first to prefer a "local" |
1367 | // reason over a more distant one. |
1368 | for (const FieldDecl *FD : RD->fields()) { |
1369 | if (FD->getAccess() != AS_public) { |
1370 | Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0; |
1371 | return true; |
1372 | } |
1373 | if (FD->isMutable()) { |
1374 | Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T; |
1375 | return true; |
1376 | } |
1377 | if (FD->getType()->isRValueReferenceType()) { |
1378 | Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field) |
1379 | << T; |
1380 | return true; |
1381 | } |
1382 | } |
1383 | |
1384 | // All bases are required to be public. |
1385 | for (const auto &BaseSpec : RD->bases()) { |
1386 | if (BaseSpec.getAccessSpecifier() != AS_public) { |
1387 | Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public) |
1388 | << T << 1; |
1389 | return true; |
1390 | } |
1391 | } |
1392 | |
1393 | // All subobjects are required to be of structural types. |
1394 | SourceLocation SubLoc; |
1395 | QualType SubType; |
1396 | int Kind = -1; |
1397 | |
1398 | for (const FieldDecl *FD : RD->fields()) { |
1399 | QualType T = Context.getBaseElementType(FD->getType()); |
1400 | if (!T->isStructuralType()) { |
1401 | SubLoc = FD->getLocation(); |
1402 | SubType = T; |
1403 | Kind = 0; |
1404 | break; |
1405 | } |
1406 | } |
1407 | |
1408 | if (Kind == -1) { |
1409 | for (const auto &BaseSpec : RD->bases()) { |
1410 | QualType T = BaseSpec.getType(); |
1411 | if (!T->isStructuralType()) { |
1412 | SubLoc = BaseSpec.getBaseTypeLoc(); |
1413 | SubType = T; |
1414 | Kind = 1; |
1415 | break; |
1416 | } |
1417 | } |
1418 | } |
1419 | |
1420 | assert(Kind != -1 && "couldn't find reason why type is not structural" ); |
1421 | Diag(SubLoc, diag::note_not_structural_subobject) |
1422 | << T << Kind << SubType; |
1423 | T = SubType; |
1424 | RD = T->getAsCXXRecordDecl(); |
1425 | } |
1426 | |
1427 | return true; |
1428 | } |
1429 | |
1430 | QualType Sema::CheckNonTypeTemplateParameterType(QualType T, |
1431 | SourceLocation Loc) { |
1432 | // We don't allow variably-modified types as the type of non-type template |
1433 | // parameters. |
1434 | if (T->isVariablyModifiedType()) { |
1435 | Diag(Loc, diag::err_variably_modified_nontype_template_param) |
1436 | << T; |
1437 | return QualType(); |
1438 | } |
1439 | |
1440 | // C++ [temp.param]p4: |
1441 | // |
1442 | // A non-type template-parameter shall have one of the following |
1443 | // (optionally cv-qualified) types: |
1444 | // |
1445 | // -- integral or enumeration type, |
1446 | if (T->isIntegralOrEnumerationType() || |
1447 | // -- pointer to object or pointer to function, |
1448 | T->isPointerType() || |
1449 | // -- lvalue reference to object or lvalue reference to function, |
1450 | T->isLValueReferenceType() || |
1451 | // -- pointer to member, |
1452 | T->isMemberPointerType() || |
1453 | // -- std::nullptr_t, or |
1454 | T->isNullPtrType() || |
1455 | // -- a type that contains a placeholder type. |
1456 | T->isUndeducedType()) { |
1457 | // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter |
1458 | // are ignored when determining its type. |
1459 | return T.getUnqualifiedType(); |
1460 | } |
1461 | |
1462 | // C++ [temp.param]p8: |
1463 | // |
1464 | // A non-type template-parameter of type "array of T" or |
1465 | // "function returning T" is adjusted to be of type "pointer to |
1466 | // T" or "pointer to function returning T", respectively. |
1467 | if (T->isArrayType() || T->isFunctionType()) |
1468 | return Context.getDecayedType(T); |
1469 | |
1470 | // If T is a dependent type, we can't do the check now, so we |
1471 | // assume that it is well-formed. Note that stripping off the |
1472 | // qualifiers here is not really correct if T turns out to be |
1473 | // an array type, but we'll recompute the type everywhere it's |
1474 | // used during instantiation, so that should be OK. (Using the |
1475 | // qualified type is equally wrong.) |
1476 | if (T->isDependentType()) |
1477 | return T.getUnqualifiedType(); |
1478 | |
1479 | // C++20 [temp.param]p6: |
1480 | // -- a structural type |
1481 | if (RequireStructuralType(T, Loc)) |
1482 | return QualType(); |
1483 | |
1484 | if (!getLangOpts().CPlusPlus20) { |
1485 | // FIXME: Consider allowing structural types as an extension in C++17. (In |
1486 | // earlier language modes, the template argument evaluation rules are too |
1487 | // inflexible.) |
1488 | Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T; |
1489 | return QualType(); |
1490 | } |
1491 | |
1492 | Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T; |
1493 | return T.getUnqualifiedType(); |
1494 | } |
1495 | |
1496 | NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, |
1497 | unsigned Depth, |
1498 | unsigned Position, |
1499 | SourceLocation EqualLoc, |
1500 | Expr *Default) { |
1501 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
1502 | |
1503 | // Check that we have valid decl-specifiers specified. |
1504 | auto CheckValidDeclSpecifiers = [this, &D] { |
1505 | // C++ [temp.param] |
1506 | // p1 |
1507 | // template-parameter: |
1508 | // ... |
1509 | // parameter-declaration |
1510 | // p2 |
1511 | // ... A storage class shall not be specified in a template-parameter |
1512 | // declaration. |
1513 | // [dcl.typedef]p1: |
1514 | // The typedef specifier [...] shall not be used in the decl-specifier-seq |
1515 | // of a parameter-declaration |
1516 | const DeclSpec &DS = D.getDeclSpec(); |
1517 | auto EmitDiag = [this](SourceLocation Loc) { |
1518 | Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm) |
1519 | << FixItHint::CreateRemoval(Loc); |
1520 | }; |
1521 | if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) |
1522 | EmitDiag(DS.getStorageClassSpecLoc()); |
1523 | |
1524 | if (DS.getThreadStorageClassSpec() != TSCS_unspecified) |
1525 | EmitDiag(DS.getThreadStorageClassSpecLoc()); |
1526 | |
1527 | // [dcl.inline]p1: |
1528 | // The inline specifier can be applied only to the declaration or |
1529 | // definition of a variable or function. |
1530 | |
1531 | if (DS.isInlineSpecified()) |
1532 | EmitDiag(DS.getInlineSpecLoc()); |
1533 | |
1534 | // [dcl.constexpr]p1: |
1535 | // The constexpr specifier shall be applied only to the definition of a |
1536 | // variable or variable template or the declaration of a function or |
1537 | // function template. |
1538 | |
1539 | if (DS.hasConstexprSpecifier()) |
1540 | EmitDiag(DS.getConstexprSpecLoc()); |
1541 | |
1542 | // [dcl.fct.spec]p1: |
1543 | // Function-specifiers can be used only in function declarations. |
1544 | |
1545 | if (DS.isVirtualSpecified()) |
1546 | EmitDiag(DS.getVirtualSpecLoc()); |
1547 | |
1548 | if (DS.hasExplicitSpecifier()) |
1549 | EmitDiag(DS.getExplicitSpecLoc()); |
1550 | |
1551 | if (DS.isNoreturnSpecified()) |
1552 | EmitDiag(DS.getNoreturnSpecLoc()); |
1553 | }; |
1554 | |
1555 | CheckValidDeclSpecifiers(); |
1556 | |
1557 | if (const auto *T = TInfo->getType()->getContainedDeducedType()) |
1558 | if (isa<AutoType>(T)) |
1559 | Diag(D.getIdentifierLoc(), |
1560 | diag::warn_cxx14_compat_template_nontype_parm_auto_type) |
1561 | << QualType(TInfo->getType()->getContainedAutoType(), 0); |
1562 | |
1563 | assert(S->isTemplateParamScope() && |
1564 | "Non-type template parameter not in template parameter scope!" ); |
1565 | bool Invalid = false; |
1566 | |
1567 | QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc()); |
1568 | if (T.isNull()) { |
1569 | T = Context.IntTy; // Recover with an 'int' type. |
1570 | Invalid = true; |
1571 | } |
1572 | |
1573 | CheckFunctionOrTemplateParamDeclarator(S, D); |
1574 | |
1575 | IdentifierInfo *ParamName = D.getIdentifier(); |
1576 | bool IsParameterPack = D.hasEllipsis(); |
1577 | NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create( |
1578 | Context, Context.getTranslationUnitDecl(), D.getBeginLoc(), |
1579 | D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack, |
1580 | TInfo); |
1581 | Param->setAccess(AS_public); |
1582 | |
1583 | if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) |
1584 | if (TL.isConstrained()) |
1585 | if (AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc())) |
1586 | Invalid = true; |
1587 | |
1588 | if (Invalid) |
1589 | Param->setInvalidDecl(); |
1590 | |
1591 | if (Param->isParameterPack()) |
1592 | if (auto *LSI = getEnclosingLambda()) |
1593 | LSI->LocalPacks.push_back(Param); |
1594 | |
1595 | if (ParamName) { |
1596 | maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(), |
1597 | Name: ParamName); |
1598 | |
1599 | // Add the template parameter into the current scope. |
1600 | S->AddDecl(Param); |
1601 | IdResolver.AddDecl(Param); |
1602 | } |
1603 | |
1604 | // C++0x [temp.param]p9: |
1605 | // A default template-argument may be specified for any kind of |
1606 | // template-parameter that is not a template parameter pack. |
1607 | if (Default && IsParameterPack) { |
1608 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
1609 | Default = nullptr; |
1610 | } |
1611 | |
1612 | // Check the well-formedness of the default template argument, if provided. |
1613 | if (Default) { |
1614 | // Check for unexpanded parameter packs. |
1615 | if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument)) |
1616 | return Param; |
1617 | |
1618 | Param->setDefaultArgument(Default); |
1619 | } |
1620 | |
1621 | return Param; |
1622 | } |
1623 | |
1624 | /// ActOnTemplateTemplateParameter - Called when a C++ template template |
1625 | /// parameter (e.g. T in template <template \<typename> class T> class array) |
1626 | /// has been parsed. S is the current scope. |
1627 | NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S, |
1628 | SourceLocation TmpLoc, |
1629 | TemplateParameterList *Params, |
1630 | SourceLocation EllipsisLoc, |
1631 | IdentifierInfo *Name, |
1632 | SourceLocation NameLoc, |
1633 | unsigned Depth, |
1634 | unsigned Position, |
1635 | SourceLocation EqualLoc, |
1636 | ParsedTemplateArgument Default) { |
1637 | assert(S->isTemplateParamScope() && |
1638 | "Template template parameter not in template parameter scope!" ); |
1639 | |
1640 | // Construct the parameter object. |
1641 | bool IsParameterPack = EllipsisLoc.isValid(); |
1642 | TemplateTemplateParmDecl *Param = |
1643 | TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
1644 | NameLoc.isInvalid()? TmpLoc : NameLoc, |
1645 | Depth, Position, IsParameterPack, |
1646 | Name, Params); |
1647 | Param->setAccess(AS_public); |
1648 | |
1649 | if (Param->isParameterPack()) |
1650 | if (auto *LSI = getEnclosingLambda()) |
1651 | LSI->LocalPacks.push_back(Param); |
1652 | |
1653 | // If the template template parameter has a name, then link the identifier |
1654 | // into the scope and lookup mechanisms. |
1655 | if (Name) { |
1656 | maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name); |
1657 | |
1658 | S->AddDecl(Param); |
1659 | IdResolver.AddDecl(Param); |
1660 | } |
1661 | |
1662 | if (Params->size() == 0) { |
1663 | Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) |
1664 | << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); |
1665 | Param->setInvalidDecl(); |
1666 | } |
1667 | |
1668 | // C++0x [temp.param]p9: |
1669 | // A default template-argument may be specified for any kind of |
1670 | // template-parameter that is not a template parameter pack. |
1671 | if (IsParameterPack && !Default.isInvalid()) { |
1672 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
1673 | Default = ParsedTemplateArgument(); |
1674 | } |
1675 | |
1676 | if (!Default.isInvalid()) { |
1677 | // Check only that we have a template template argument. We don't want to |
1678 | // try to check well-formedness now, because our template template parameter |
1679 | // might have dependent types in its template parameters, which we wouldn't |
1680 | // be able to match now. |
1681 | // |
1682 | // If none of the template template parameter's template arguments mention |
1683 | // other template parameters, we could actually perform more checking here. |
1684 | // However, it isn't worth doing. |
1685 | TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default); |
1686 | if (DefaultArg.getArgument().getAsTemplate().isNull()) { |
1687 | Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template) |
1688 | << DefaultArg.getSourceRange(); |
1689 | return Param; |
1690 | } |
1691 | |
1692 | // Check for unexpanded parameter packs. |
1693 | if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(), |
1694 | Template: DefaultArg.getArgument().getAsTemplate(), |
1695 | UPPC: UPPC_DefaultArgument)) |
1696 | return Param; |
1697 | |
1698 | Param->setDefaultArgument(C: Context, DefArg: DefaultArg); |
1699 | } |
1700 | |
1701 | return Param; |
1702 | } |
1703 | |
1704 | namespace { |
1705 | class ConstraintRefersToContainingTemplateChecker |
1706 | : public TreeTransform<ConstraintRefersToContainingTemplateChecker> { |
1707 | bool Result = false; |
1708 | const FunctionDecl *Friend = nullptr; |
1709 | unsigned TemplateDepth = 0; |
1710 | |
1711 | // Check a record-decl that we've seen to see if it is a lexical parent of the |
1712 | // Friend, likely because it was referred to without its template arguments. |
1713 | void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) { |
1714 | CheckingRD = CheckingRD->getMostRecentDecl(); |
1715 | if (!CheckingRD->isTemplated()) |
1716 | return; |
1717 | |
1718 | for (const DeclContext *DC = Friend->getLexicalDeclContext(); |
1719 | DC && !DC->isFileContext(); DC = DC->getParent()) |
1720 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) |
1721 | if (CheckingRD == RD->getMostRecentDecl()) |
1722 | Result = true; |
1723 | } |
1724 | |
1725 | void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { |
1726 | assert(D->getDepth() <= TemplateDepth && |
1727 | "Nothing should reference a value below the actual template depth, " |
1728 | "depth is likely wrong" ); |
1729 | if (D->getDepth() != TemplateDepth) |
1730 | Result = true; |
1731 | |
1732 | // Necessary because the type of the NTTP might be what refers to the parent |
1733 | // constriant. |
1734 | TransformType(D->getType()); |
1735 | } |
1736 | |
1737 | public: |
1738 | using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>; |
1739 | |
1740 | ConstraintRefersToContainingTemplateChecker(Sema &SemaRef, |
1741 | const FunctionDecl *Friend, |
1742 | unsigned TemplateDepth) |
1743 | : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {} |
1744 | bool getResult() const { return Result; } |
1745 | |
1746 | // This should be the only template parm type that we have to deal with. |
1747 | // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and |
1748 | // FunctionParmPackExpr are all partially substituted, which cannot happen |
1749 | // with concepts at this point in translation. |
1750 | using inherited::TransformTemplateTypeParmType; |
1751 | QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
1752 | TemplateTypeParmTypeLoc TL, bool) { |
1753 | assert(TL.getDecl()->getDepth() <= TemplateDepth && |
1754 | "Nothing should reference a value below the actual template depth, " |
1755 | "depth is likely wrong" ); |
1756 | if (TL.getDecl()->getDepth() != TemplateDepth) |
1757 | Result = true; |
1758 | return inherited::TransformTemplateTypeParmType( |
1759 | TLB, TL, |
1760 | /*SuppressObjCLifetime=*/false); |
1761 | } |
1762 | |
1763 | Decl *TransformDecl(SourceLocation Loc, Decl *D) { |
1764 | if (!D) |
1765 | return D; |
1766 | // FIXME : This is possibly an incomplete list, but it is unclear what other |
1767 | // Decl kinds could be used to refer to the template parameters. This is a |
1768 | // best guess so far based on examples currently available, but the |
1769 | // unreachable should catch future instances/cases. |
1770 | if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) |
1771 | TransformType(TD->getUnderlyingType()); |
1772 | else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) |
1773 | CheckNonTypeTemplateParmDecl(D: NTTPD); |
1774 | else if (auto *VD = dyn_cast<ValueDecl>(Val: D)) |
1775 | TransformType(VD->getType()); |
1776 | else if (auto *TD = dyn_cast<TemplateDecl>(Val: D)) |
1777 | TransformTemplateParameterList(TD->getTemplateParameters()); |
1778 | else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
1779 | CheckIfContainingRecord(CheckingRD: RD); |
1780 | else if (isa<NamedDecl>(Val: D)) { |
1781 | // No direct types to visit here I believe. |
1782 | } else |
1783 | llvm_unreachable("Don't know how to handle this declaration type yet" ); |
1784 | return D; |
1785 | } |
1786 | }; |
1787 | } // namespace |
1788 | |
1789 | bool Sema::ConstraintExpressionDependsOnEnclosingTemplate( |
1790 | const FunctionDecl *Friend, unsigned TemplateDepth, |
1791 | const Expr *Constraint) { |
1792 | assert(Friend->getFriendObjectKind() && "Only works on a friend" ); |
1793 | ConstraintRefersToContainingTemplateChecker Checker(*this, Friend, |
1794 | TemplateDepth); |
1795 | Checker.TransformExpr(const_cast<Expr *>(Constraint)); |
1796 | return Checker.getResult(); |
1797 | } |
1798 | |
1799 | /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally |
1800 | /// constrained by RequiresClause, that contains the template parameters in |
1801 | /// Params. |
1802 | TemplateParameterList * |
1803 | Sema::ActOnTemplateParameterList(unsigned Depth, |
1804 | SourceLocation ExportLoc, |
1805 | SourceLocation TemplateLoc, |
1806 | SourceLocation LAngleLoc, |
1807 | ArrayRef<NamedDecl *> Params, |
1808 | SourceLocation RAngleLoc, |
1809 | Expr *RequiresClause) { |
1810 | if (ExportLoc.isValid()) |
1811 | Diag(ExportLoc, diag::warn_template_export_unsupported); |
1812 | |
1813 | for (NamedDecl *P : Params) |
1814 | warnOnReservedIdentifier(D: P); |
1815 | |
1816 | return TemplateParameterList::Create( |
1817 | C: Context, TemplateLoc, LAngleLoc, |
1818 | Params: llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause); |
1819 | } |
1820 | |
1821 | static void SetNestedNameSpecifier(Sema &S, TagDecl *T, |
1822 | const CXXScopeSpec &SS) { |
1823 | if (SS.isSet()) |
1824 | T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context)); |
1825 | } |
1826 | |
1827 | // Returns the template parameter list with all default template argument |
1828 | // information. |
1829 | static TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD) { |
1830 | // Make sure we get the template parameter list from the most |
1831 | // recent declaration, since that is the only one that is guaranteed to |
1832 | // have all the default template argument information. |
1833 | return cast<TemplateDecl>(TD->getMostRecentDecl())->getTemplateParameters(); |
1834 | } |
1835 | |
1836 | DeclResult Sema::CheckClassTemplate( |
1837 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
1838 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, |
1839 | const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, |
1840 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
1841 | SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, |
1842 | TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) { |
1843 | assert(TemplateParams && TemplateParams->size() > 0 && |
1844 | "No template parameters" ); |
1845 | assert(TUK != TUK_Reference && "Can only declare or define class templates" ); |
1846 | bool Invalid = false; |
1847 | |
1848 | // Check that we can declare a template here. |
1849 | if (CheckTemplateDeclScope(S, TemplateParams)) |
1850 | return true; |
1851 | |
1852 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec); |
1853 | assert(Kind != TagTypeKind::Enum && |
1854 | "can't build template of enumerated type" ); |
1855 | |
1856 | // There is no such thing as an unnamed class template. |
1857 | if (!Name) { |
1858 | Diag(KWLoc, diag::err_template_unnamed_class); |
1859 | return true; |
1860 | } |
1861 | |
1862 | // Find any previous declaration with this name. For a friend with no |
1863 | // scope explicitly specified, we only look for tag declarations (per |
1864 | // C++11 [basic.lookup.elab]p2). |
1865 | DeclContext *SemanticContext; |
1866 | LookupResult Previous(*this, Name, NameLoc, |
1867 | (SS.isEmpty() && TUK == TUK_Friend) |
1868 | ? LookupTagName : LookupOrdinaryName, |
1869 | forRedeclarationInCurContext()); |
1870 | if (SS.isNotEmpty() && !SS.isInvalid()) { |
1871 | SemanticContext = computeDeclContext(SS, EnteringContext: true); |
1872 | if (!SemanticContext) { |
1873 | // FIXME: Horrible, horrible hack! We can't currently represent this |
1874 | // in the AST, and historically we have just ignored such friend |
1875 | // class templates, so don't complain here. |
1876 | Diag(NameLoc, TUK == TUK_Friend |
1877 | ? diag::warn_template_qualified_friend_ignored |
1878 | : diag::err_template_qualified_declarator_no_match) |
1879 | << SS.getScopeRep() << SS.getRange(); |
1880 | return TUK != TUK_Friend; |
1881 | } |
1882 | |
1883 | if (RequireCompleteDeclContext(SS, DC: SemanticContext)) |
1884 | return true; |
1885 | |
1886 | // If we're adding a template to a dependent context, we may need to |
1887 | // rebuilding some of the types used within the template parameter list, |
1888 | // now that we know what the current instantiation is. |
1889 | if (SemanticContext->isDependentContext()) { |
1890 | ContextRAII SavedContext(*this, SemanticContext); |
1891 | if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams)) |
1892 | Invalid = true; |
1893 | } |
1894 | |
1895 | if (TUK != TUK_Friend && TUK != TUK_Reference) |
1896 | diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc, |
1897 | /*TemplateId-*/ TemplateId: nullptr, |
1898 | /*IsMemberSpecialization*/ false); |
1899 | |
1900 | LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext); |
1901 | } else { |
1902 | SemanticContext = CurContext; |
1903 | |
1904 | // C++14 [class.mem]p14: |
1905 | // If T is the name of a class, then each of the following shall have a |
1906 | // name different from T: |
1907 | // -- every member template of class T |
1908 | if (TUK != TUK_Friend && |
1909 | DiagnoseClassNameShadow(DC: SemanticContext, |
1910 | Info: DeclarationNameInfo(Name, NameLoc))) |
1911 | return true; |
1912 | |
1913 | LookupName(R&: Previous, S); |
1914 | } |
1915 | |
1916 | if (Previous.isAmbiguous()) |
1917 | return true; |
1918 | |
1919 | NamedDecl *PrevDecl = nullptr; |
1920 | if (Previous.begin() != Previous.end()) |
1921 | PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
1922 | |
1923 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
1924 | // Maybe we will complain about the shadowed template parameter. |
1925 | DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); |
1926 | // Just pretend that we didn't see the previous declaration. |
1927 | PrevDecl = nullptr; |
1928 | } |
1929 | |
1930 | // If there is a previous declaration with the same name, check |
1931 | // whether this is a valid redeclaration. |
1932 | ClassTemplateDecl *PrevClassTemplate = |
1933 | dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl); |
1934 | |
1935 | // We may have found the injected-class-name of a class template, |
1936 | // class template partial specialization, or class template specialization. |
1937 | // In these cases, grab the template that is being defined or specialized. |
1938 | if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(Val: PrevDecl) && |
1939 | cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) { |
1940 | PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); |
1941 | PrevClassTemplate |
1942 | = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate(); |
1943 | if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) { |
1944 | PrevClassTemplate |
1945 | = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl) |
1946 | ->getSpecializedTemplate(); |
1947 | } |
1948 | } |
1949 | |
1950 | if (TUK == TUK_Friend) { |
1951 | // C++ [namespace.memdef]p3: |
1952 | // [...] When looking for a prior declaration of a class or a function |
1953 | // declared as a friend, and when the name of the friend class or |
1954 | // function is neither a qualified name nor a template-id, scopes outside |
1955 | // the innermost enclosing namespace scope are not considered. |
1956 | if (!SS.isSet()) { |
1957 | DeclContext *OutermostContext = CurContext; |
1958 | while (!OutermostContext->isFileContext()) |
1959 | OutermostContext = OutermostContext->getLookupParent(); |
1960 | |
1961 | if (PrevDecl && |
1962 | (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) || |
1963 | OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) { |
1964 | SemanticContext = PrevDecl->getDeclContext(); |
1965 | } else { |
1966 | // Declarations in outer scopes don't matter. However, the outermost |
1967 | // context we computed is the semantic context for our new |
1968 | // declaration. |
1969 | PrevDecl = PrevClassTemplate = nullptr; |
1970 | SemanticContext = OutermostContext; |
1971 | |
1972 | // Check that the chosen semantic context doesn't already contain a |
1973 | // declaration of this name as a non-tag type. |
1974 | Previous.clear(Kind: LookupOrdinaryName); |
1975 | DeclContext *LookupContext = SemanticContext; |
1976 | while (LookupContext->isTransparentContext()) |
1977 | LookupContext = LookupContext->getLookupParent(); |
1978 | LookupQualifiedName(R&: Previous, LookupCtx: LookupContext); |
1979 | |
1980 | if (Previous.isAmbiguous()) |
1981 | return true; |
1982 | |
1983 | if (Previous.begin() != Previous.end()) |
1984 | PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
1985 | } |
1986 | } |
1987 | } else if (PrevDecl && |
1988 | !isDeclInScope(D: Previous.getRepresentativeDecl(), Ctx: SemanticContext, |
1989 | S, AllowInlineNamespace: SS.isValid())) |
1990 | PrevDecl = PrevClassTemplate = nullptr; |
1991 | |
1992 | if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>( |
1993 | Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) { |
1994 | if (SS.isEmpty() && |
1995 | !(PrevClassTemplate && |
1996 | PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals( |
1997 | SemanticContext->getRedeclContext()))) { |
1998 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); |
1999 | Diag(Shadow->getTargetDecl()->getLocation(), |
2000 | diag::note_using_decl_target); |
2001 | Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0; |
2002 | // Recover by ignoring the old declaration. |
2003 | PrevDecl = PrevClassTemplate = nullptr; |
2004 | } |
2005 | } |
2006 | |
2007 | if (PrevClassTemplate) { |
2008 | // Ensure that the template parameter lists are compatible. Skip this check |
2009 | // for a friend in a dependent context: the template parameter list itself |
2010 | // could be dependent. |
2011 | if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
2012 | !TemplateParameterListsAreEqual( |
2013 | TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext |
2014 | : CurContext, |
2015 | CurContext, KWLoc), |
2016 | TemplateParams, PrevClassTemplate, |
2017 | PrevClassTemplate->getTemplateParameters(), /*Complain=*/true, |
2018 | TPL_TemplateMatch)) |
2019 | return true; |
2020 | |
2021 | // C++ [temp.class]p4: |
2022 | // In a redeclaration, partial specialization, explicit |
2023 | // specialization or explicit instantiation of a class template, |
2024 | // the class-key shall agree in kind with the original class |
2025 | // template declaration (7.1.5.3). |
2026 | RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); |
2027 | if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, |
2028 | TUK == TUK_Definition, KWLoc, Name)) { |
2029 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
2030 | << Name |
2031 | << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); |
2032 | Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); |
2033 | Kind = PrevRecordDecl->getTagKind(); |
2034 | } |
2035 | |
2036 | // Check for redefinition of this class template. |
2037 | if (TUK == TUK_Definition) { |
2038 | if (TagDecl *Def = PrevRecordDecl->getDefinition()) { |
2039 | // If we have a prior definition that is not visible, treat this as |
2040 | // simply making that previous definition visible. |
2041 | NamedDecl *Hidden = nullptr; |
2042 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { |
2043 | SkipBody->ShouldSkip = true; |
2044 | SkipBody->Previous = Def; |
2045 | auto *Tmpl = cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate(); |
2046 | assert(Tmpl && "original definition of a class template is not a " |
2047 | "class template?" ); |
2048 | makeMergedDefinitionVisible(ND: Hidden); |
2049 | makeMergedDefinitionVisible(Tmpl); |
2050 | } else { |
2051 | Diag(NameLoc, diag::err_redefinition) << Name; |
2052 | Diag(Def->getLocation(), diag::note_previous_definition); |
2053 | // FIXME: Would it make sense to try to "forget" the previous |
2054 | // definition, as part of error recovery? |
2055 | return true; |
2056 | } |
2057 | } |
2058 | } |
2059 | } else if (PrevDecl) { |
2060 | // C++ [temp]p5: |
2061 | // A class template shall not have the same name as any other |
2062 | // template, class, function, object, enumeration, enumerator, |
2063 | // namespace, or type in the same scope (3.3), except as specified |
2064 | // in (14.5.4). |
2065 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; |
2066 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); |
2067 | return true; |
2068 | } |
2069 | |
2070 | // Check the template parameter list of this declaration, possibly |
2071 | // merging in the template parameter list from the previous class |
2072 | // template declaration. Skip this check for a friend in a dependent |
2073 | // context, because the template parameter list might be dependent. |
2074 | if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
2075 | CheckTemplateParameterList( |
2076 | NewParams: TemplateParams, |
2077 | OldParams: PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate) |
2078 | : nullptr, |
2079 | TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() && |
2080 | SemanticContext->isDependentContext()) |
2081 | ? TPC_ClassTemplateMember |
2082 | : TUK == TUK_Friend ? TPC_FriendClassTemplate |
2083 | : TPC_ClassTemplate, |
2084 | SkipBody)) |
2085 | Invalid = true; |
2086 | |
2087 | if (SS.isSet()) { |
2088 | // If the name of the template was qualified, we must be defining the |
2089 | // template out-of-line. |
2090 | if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { |
2091 | Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match |
2092 | : diag::err_member_decl_does_not_match) |
2093 | << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); |
2094 | Invalid = true; |
2095 | } |
2096 | } |
2097 | |
2098 | // If this is a templated friend in a dependent context we should not put it |
2099 | // on the redecl chain. In some cases, the templated friend can be the most |
2100 | // recent declaration tricking the template instantiator to make substitutions |
2101 | // there. |
2102 | // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious |
2103 | bool ShouldAddRedecl |
2104 | = !(TUK == TUK_Friend && CurContext->isDependentContext()); |
2105 | |
2106 | CXXRecordDecl *NewClass = |
2107 | CXXRecordDecl::Create(C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name, |
2108 | PrevDecl: PrevClassTemplate && ShouldAddRedecl ? |
2109 | PrevClassTemplate->getTemplatedDecl() : nullptr, |
2110 | /*DelayTypeCreation=*/true); |
2111 | SetNestedNameSpecifier(*this, NewClass, SS); |
2112 | if (NumOuterTemplateParamLists > 0) |
2113 | NewClass->setTemplateParameterListsInfo( |
2114 | Context, |
2115 | llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists)); |
2116 | |
2117 | // Add alignment attributes if necessary; these attributes are checked when |
2118 | // the ASTContext lays out the structure. |
2119 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
2120 | AddAlignmentAttributesForRecord(NewClass); |
2121 | AddMsStructLayoutForRecord(NewClass); |
2122 | } |
2123 | |
2124 | ClassTemplateDecl *NewTemplate |
2125 | = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, |
2126 | DeclarationName(Name), TemplateParams, |
2127 | NewClass); |
2128 | |
2129 | if (ShouldAddRedecl) |
2130 | NewTemplate->setPreviousDecl(PrevClassTemplate); |
2131 | |
2132 | NewClass->setDescribedClassTemplate(NewTemplate); |
2133 | |
2134 | if (ModulePrivateLoc.isValid()) |
2135 | NewTemplate->setModulePrivate(); |
2136 | |
2137 | // Build the type for the class template declaration now. |
2138 | QualType T = NewTemplate->getInjectedClassNameSpecialization(); |
2139 | T = Context.getInjectedClassNameType(Decl: NewClass, TST: T); |
2140 | assert(T->isDependentType() && "Class template type is not dependent?" ); |
2141 | (void)T; |
2142 | |
2143 | // If we are providing an explicit specialization of a member that is a |
2144 | // class template, make a note of that. |
2145 | if (PrevClassTemplate && |
2146 | PrevClassTemplate->getInstantiatedFromMemberTemplate()) |
2147 | PrevClassTemplate->setMemberSpecialization(); |
2148 | |
2149 | // Set the access specifier. |
2150 | if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) |
2151 | SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); |
2152 | |
2153 | // Set the lexical context of these templates |
2154 | NewClass->setLexicalDeclContext(CurContext); |
2155 | NewTemplate->setLexicalDeclContext(CurContext); |
2156 | |
2157 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) |
2158 | NewClass->startDefinition(); |
2159 | |
2160 | ProcessDeclAttributeList(S, NewClass, Attr); |
2161 | |
2162 | if (PrevClassTemplate) |
2163 | mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); |
2164 | |
2165 | AddPushedVisibilityAttribute(NewClass); |
2166 | inferGslOwnerPointerAttribute(Record: NewClass); |
2167 | |
2168 | if (TUK != TUK_Friend) { |
2169 | // Per C++ [basic.scope.temp]p2, skip the template parameter scopes. |
2170 | Scope *Outer = S; |
2171 | while ((Outer->getFlags() & Scope::TemplateParamScope) != 0) |
2172 | Outer = Outer->getParent(); |
2173 | PushOnScopeChains(NewTemplate, Outer); |
2174 | } else { |
2175 | if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { |
2176 | NewTemplate->setAccess(PrevClassTemplate->getAccess()); |
2177 | NewClass->setAccess(PrevClassTemplate->getAccess()); |
2178 | } |
2179 | |
2180 | NewTemplate->setObjectOfFriendDecl(); |
2181 | |
2182 | // Friend templates are visible in fairly strange ways. |
2183 | if (!CurContext->isDependentContext()) { |
2184 | DeclContext *DC = SemanticContext->getRedeclContext(); |
2185 | DC->makeDeclVisibleInContext(NewTemplate); |
2186 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) |
2187 | PushOnScopeChains(NewTemplate, EnclosingScope, |
2188 | /* AddToContext = */ false); |
2189 | } |
2190 | |
2191 | FriendDecl *Friend = FriendDecl::Create( |
2192 | C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc); |
2193 | Friend->setAccess(AS_public); |
2194 | CurContext->addDecl(Friend); |
2195 | } |
2196 | |
2197 | if (PrevClassTemplate) |
2198 | CheckRedeclarationInModule(NewTemplate, PrevClassTemplate); |
2199 | |
2200 | if (Invalid) { |
2201 | NewTemplate->setInvalidDecl(); |
2202 | NewClass->setInvalidDecl(); |
2203 | } |
2204 | |
2205 | ActOnDocumentableDecl(NewTemplate); |
2206 | |
2207 | if (SkipBody && SkipBody->ShouldSkip) |
2208 | return SkipBody->Previous; |
2209 | |
2210 | return NewTemplate; |
2211 | } |
2212 | |
2213 | namespace { |
2214 | /// Tree transform to "extract" a transformed type from a class template's |
2215 | /// constructor to a deduction guide. |
2216 | class |
2217 | : public TreeTransform<ExtractTypeForDeductionGuide> { |
2218 | llvm::SmallVectorImpl<TypedefNameDecl *> &; |
2219 | |
2220 | public: |
2221 | typedef TreeTransform<ExtractTypeForDeductionGuide> ; |
2222 | ( |
2223 | Sema &SemaRef, |
2224 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) |
2225 | : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} |
2226 | |
2227 | TypeSourceInfo *(TypeSourceInfo *TSI) { return TransformType(TSI); } |
2228 | |
2229 | QualType (TypeLocBuilder &TLB, TypedefTypeLoc TL) { |
2230 | ASTContext &Context = SemaRef.getASTContext(); |
2231 | TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl(); |
2232 | TypedefNameDecl *Decl = OrigDecl; |
2233 | // Transform the underlying type of the typedef and clone the Decl only if |
2234 | // the typedef has a dependent context. |
2235 | if (OrigDecl->getDeclContext()->isDependentContext()) { |
2236 | TypeLocBuilder InnerTLB; |
2237 | QualType Transformed = |
2238 | TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc()); |
2239 | TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, T: Transformed); |
2240 | if (isa<TypeAliasDecl>(Val: OrigDecl)) |
2241 | Decl = TypeAliasDecl::Create( |
2242 | C&: Context, DC: Context.getTranslationUnitDecl(), StartLoc: OrigDecl->getBeginLoc(), |
2243 | IdLoc: OrigDecl->getLocation(), Id: OrigDecl->getIdentifier(), TInfo: TSI); |
2244 | else { |
2245 | assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef" ); |
2246 | Decl = TypedefDecl::Create( |
2247 | C&: Context, DC: Context.getTranslationUnitDecl(), StartLoc: OrigDecl->getBeginLoc(), |
2248 | IdLoc: OrigDecl->getLocation(), Id: OrigDecl->getIdentifier(), TInfo: TSI); |
2249 | } |
2250 | MaterializedTypedefs.push_back(Elt: Decl); |
2251 | } |
2252 | |
2253 | QualType TDTy = Context.getTypedefType(Decl); |
2254 | TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T: TDTy); |
2255 | TypedefTL.setNameLoc(TL.getNameLoc()); |
2256 | |
2257 | return TDTy; |
2258 | } |
2259 | }; |
2260 | |
2261 | /// Transform to convert portions of a constructor declaration into the |
2262 | /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. |
2263 | struct ConvertConstructorToDeductionGuideTransform { |
2264 | ConvertConstructorToDeductionGuideTransform(Sema &S, |
2265 | ClassTemplateDecl *Template) |
2266 | : SemaRef(S), Template(Template) { |
2267 | // If the template is nested, then we need to use the original |
2268 | // pattern to iterate over the constructors. |
2269 | ClassTemplateDecl *Pattern = Template; |
2270 | while (Pattern->getInstantiatedFromMemberTemplate()) { |
2271 | if (Pattern->isMemberSpecialization()) |
2272 | break; |
2273 | Pattern = Pattern->getInstantiatedFromMemberTemplate(); |
2274 | NestedPattern = Pattern; |
2275 | } |
2276 | |
2277 | if (NestedPattern) |
2278 | OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template); |
2279 | } |
2280 | |
2281 | Sema &SemaRef; |
2282 | ClassTemplateDecl *Template; |
2283 | ClassTemplateDecl *NestedPattern = nullptr; |
2284 | |
2285 | DeclContext *DC = Template->getDeclContext(); |
2286 | CXXRecordDecl *Primary = Template->getTemplatedDecl(); |
2287 | DeclarationName DeductionGuideName = |
2288 | SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template); |
2289 | |
2290 | QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary); |
2291 | |
2292 | // Index adjustment to apply to convert depth-1 template parameters into |
2293 | // depth-0 template parameters. |
2294 | unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size(); |
2295 | |
2296 | // Instantiation arguments for the outermost depth-1 templates |
2297 | // when the template is nested |
2298 | MultiLevelTemplateArgumentList OuterInstantiationArgs; |
2299 | |
2300 | /// Transform a constructor declaration into a deduction guide. |
2301 | NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, |
2302 | CXXConstructorDecl *CD) { |
2303 | SmallVector<TemplateArgument, 16> SubstArgs; |
2304 | |
2305 | LocalInstantiationScope Scope(SemaRef); |
2306 | |
2307 | // C++ [over.match.class.deduct]p1: |
2308 | // -- For each constructor of the class template designated by the |
2309 | // template-name, a function template with the following properties: |
2310 | |
2311 | // -- The template parameters are the template parameters of the class |
2312 | // template followed by the template parameters (including default |
2313 | // template arguments) of the constructor, if any. |
2314 | TemplateParameterList *TemplateParams = GetTemplateParameterList(Template); |
2315 | if (FTD) { |
2316 | TemplateParameterList *InnerParams = FTD->getTemplateParameters(); |
2317 | SmallVector<NamedDecl *, 16> AllParams; |
2318 | SmallVector<TemplateArgument, 16> Depth1Args; |
2319 | AllParams.reserve(N: TemplateParams->size() + InnerParams->size()); |
2320 | AllParams.insert(I: AllParams.begin(), |
2321 | From: TemplateParams->begin(), To: TemplateParams->end()); |
2322 | SubstArgs.reserve(N: InnerParams->size()); |
2323 | Depth1Args.reserve(N: InnerParams->size()); |
2324 | |
2325 | // Later template parameters could refer to earlier ones, so build up |
2326 | // a list of substituted template arguments as we go. |
2327 | for (NamedDecl *Param : *InnerParams) { |
2328 | MultiLevelTemplateArgumentList Args; |
2329 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
2330 | Args.addOuterTemplateArguments(Depth1Args); |
2331 | Args.addOuterRetainedLevel(); |
2332 | if (NestedPattern) |
2333 | Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth()); |
2334 | NamedDecl *NewParam = transformTemplateParameter(Param, Args); |
2335 | if (!NewParam) |
2336 | return nullptr; |
2337 | |
2338 | // Constraints require that we substitute depth-1 arguments |
2339 | // to match depths when substituted for evaluation later |
2340 | Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument( |
2341 | SemaRef.Context.getInjectedTemplateArg(NewParam))); |
2342 | |
2343 | if (NestedPattern) { |
2344 | TemplateDeclInstantiator Instantiator(SemaRef, DC, |
2345 | OuterInstantiationArgs); |
2346 | Instantiator.setEvaluateConstraints(false); |
2347 | SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] { |
2348 | NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam)); |
2349 | }); |
2350 | } |
2351 | |
2352 | assert(NewParam->getTemplateDepth() == 0 && |
2353 | "Unexpected template parameter depth" ); |
2354 | |
2355 | AllParams.push_back(NewParam); |
2356 | SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument( |
2357 | SemaRef.Context.getInjectedTemplateArg(NewParam))); |
2358 | } |
2359 | |
2360 | // Substitute new template parameters into requires-clause if present. |
2361 | Expr *RequiresClause = nullptr; |
2362 | if (Expr *InnerRC = InnerParams->getRequiresClause()) { |
2363 | MultiLevelTemplateArgumentList Args; |
2364 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
2365 | Args.addOuterTemplateArguments(Args: Depth1Args); |
2366 | Args.addOuterRetainedLevel(); |
2367 | if (NestedPattern) |
2368 | Args.addOuterRetainedLevels(Num: NestedPattern->getTemplateDepth()); |
2369 | ExprResult E = SemaRef.SubstExpr(E: InnerRC, TemplateArgs: Args); |
2370 | if (E.isInvalid()) |
2371 | return nullptr; |
2372 | RequiresClause = E.getAs<Expr>(); |
2373 | } |
2374 | |
2375 | TemplateParams = TemplateParameterList::Create( |
2376 | C: SemaRef.Context, TemplateLoc: InnerParams->getTemplateLoc(), |
2377 | LAngleLoc: InnerParams->getLAngleLoc(), Params: AllParams, RAngleLoc: InnerParams->getRAngleLoc(), |
2378 | RequiresClause); |
2379 | } |
2380 | |
2381 | // If we built a new template-parameter-list, track that we need to |
2382 | // substitute references to the old parameters into references to the |
2383 | // new ones. |
2384 | MultiLevelTemplateArgumentList Args; |
2385 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
2386 | if (FTD) { |
2387 | Args.addOuterTemplateArguments(Args: SubstArgs); |
2388 | Args.addOuterRetainedLevel(); |
2389 | } |
2390 | |
2391 | if (NestedPattern) |
2392 | Args.addOuterRetainedLevels(Num: NestedPattern->getTemplateDepth()); |
2393 | |
2394 | FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc() |
2395 | .getAsAdjusted<FunctionProtoTypeLoc>(); |
2396 | assert(FPTL && "no prototype for constructor declaration" ); |
2397 | |
2398 | // Transform the type of the function, adjusting the return type and |
2399 | // replacing references to the old parameters with references to the |
2400 | // new ones. |
2401 | TypeLocBuilder TLB; |
2402 | SmallVector<ParmVarDecl*, 8> Params; |
2403 | SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs; |
2404 | QualType NewType = transformFunctionProtoType(TLB, TL: FPTL, Params, Args, |
2405 | MaterializedTypedefs); |
2406 | if (NewType.isNull()) |
2407 | return nullptr; |
2408 | TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(Context&: SemaRef.Context, T: NewType); |
2409 | |
2410 | return buildDeductionGuide(TemplateParams, Ctor: CD, ES: CD->getExplicitSpecifier(), |
2411 | TInfo: NewTInfo, LocStart: CD->getBeginLoc(), Loc: CD->getLocation(), |
2412 | LocEnd: CD->getEndLoc(), MaterializedTypedefs); |
2413 | } |
2414 | |
2415 | /// Build a deduction guide with the specified parameter types. |
2416 | NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) { |
2417 | SourceLocation Loc = Template->getLocation(); |
2418 | |
2419 | // Build the requested type. |
2420 | FunctionProtoType::ExtProtoInfo EPI; |
2421 | EPI.HasTrailingReturn = true; |
2422 | QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc, |
2423 | DeductionGuideName, EPI); |
2424 | TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T: Result, Loc); |
2425 | if (NestedPattern) |
2426 | TSI = SemaRef.SubstType(T: TSI, TemplateArgs: OuterInstantiationArgs, Loc, |
2427 | Entity: DeductionGuideName); |
2428 | |
2429 | FunctionProtoTypeLoc FPTL = |
2430 | TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>(); |
2431 | |
2432 | // Build the parameters, needed during deduction / substitution. |
2433 | SmallVector<ParmVarDecl*, 4> Params; |
2434 | for (auto T : ParamTypes) { |
2435 | auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc); |
2436 | if (NestedPattern) |
2437 | TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc, |
2438 | DeclarationName()); |
2439 | ParmVarDecl *NewParam = |
2440 | ParmVarDecl::Create(C&: SemaRef.Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr, |
2441 | T: TSI->getType(), TInfo: TSI, S: SC_None, DefArg: nullptr); |
2442 | NewParam->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size()); |
2443 | FPTL.setParam(Params.size(), NewParam); |
2444 | Params.push_back(Elt: NewParam); |
2445 | } |
2446 | |
2447 | return buildDeductionGuide(TemplateParams: GetTemplateParameterList(Template), Ctor: nullptr, |
2448 | ES: ExplicitSpecifier(), TInfo: TSI, LocStart: Loc, Loc, LocEnd: Loc); |
2449 | } |
2450 | |
2451 | private: |
2452 | /// Transform a constructor template parameter into a deduction guide template |
2453 | /// parameter, rebuilding any internal references to earlier parameters and |
2454 | /// renumbering as we go. |
2455 | NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam, |
2456 | MultiLevelTemplateArgumentList &Args) { |
2457 | if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: TemplateParam)) { |
2458 | // TemplateTypeParmDecl's index cannot be changed after creation, so |
2459 | // substitute it directly. |
2460 | auto *NewTTP = TemplateTypeParmDecl::Create( |
2461 | C: SemaRef.Context, DC, KeyLoc: TTP->getBeginLoc(), NameLoc: TTP->getLocation(), |
2462 | D: TTP->getDepth() - 1, P: Depth1IndexAdjustment + TTP->getIndex(), |
2463 | Id: TTP->getIdentifier(), Typename: TTP->wasDeclaredWithTypename(), |
2464 | ParameterPack: TTP->isParameterPack(), HasTypeConstraint: TTP->hasTypeConstraint(), |
2465 | NumExpanded: TTP->isExpandedParameterPack() |
2466 | ? std::optional<unsigned>(TTP->getNumExpansionParameters()) |
2467 | : std::nullopt); |
2468 | if (const auto *TC = TTP->getTypeConstraint()) |
2469 | SemaRef.SubstTypeConstraint(Inst: NewTTP, TC, TemplateArgs: Args, |
2470 | /*EvaluateConstraint*/ true); |
2471 | if (TTP->hasDefaultArgument()) { |
2472 | TypeSourceInfo *InstantiatedDefaultArg = |
2473 | SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args, |
2474 | TTP->getDefaultArgumentLoc(), TTP->getDeclName()); |
2475 | if (InstantiatedDefaultArg) |
2476 | NewTTP->setDefaultArgument(InstantiatedDefaultArg); |
2477 | } |
2478 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: TemplateParam, |
2479 | Inst: NewTTP); |
2480 | return NewTTP; |
2481 | } |
2482 | |
2483 | if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TemplateParam)) |
2484 | return transformTemplateParameterImpl(OldParam: TTP, Args); |
2485 | |
2486 | return transformTemplateParameterImpl( |
2487 | OldParam: cast<NonTypeTemplateParmDecl>(Val: TemplateParam), Args); |
2488 | } |
2489 | template<typename TemplateParmDecl> |
2490 | TemplateParmDecl * |
2491 | transformTemplateParameterImpl(TemplateParmDecl *OldParam, |
2492 | MultiLevelTemplateArgumentList &Args) { |
2493 | // Ask the template instantiator to do the heavy lifting for us, then adjust |
2494 | // the index of the parameter once it's done. |
2495 | auto *NewParam = |
2496 | cast<TemplateParmDecl>(SemaRef.SubstDecl(D: OldParam, Owner: DC, TemplateArgs: Args)); |
2497 | assert(NewParam->getDepth() == OldParam->getDepth() - 1 && |
2498 | "unexpected template param depth" ); |
2499 | NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment); |
2500 | return NewParam; |
2501 | } |
2502 | |
2503 | QualType transformFunctionProtoType( |
2504 | TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, |
2505 | SmallVectorImpl<ParmVarDecl *> &Params, |
2506 | MultiLevelTemplateArgumentList &Args, |
2507 | SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { |
2508 | SmallVector<QualType, 4> ParamTypes; |
2509 | const FunctionProtoType *T = TL.getTypePtr(); |
2510 | |
2511 | // -- The types of the function parameters are those of the constructor. |
2512 | for (auto *OldParam : TL.getParams()) { |
2513 | ParmVarDecl *NewParam = |
2514 | transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs); |
2515 | if (NestedPattern && NewParam) |
2516 | NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs, |
2517 | MaterializedTypedefs); |
2518 | if (!NewParam) |
2519 | return QualType(); |
2520 | ParamTypes.push_back(NewParam->getType()); |
2521 | Params.push_back(NewParam); |
2522 | } |
2523 | |
2524 | // -- The return type is the class template specialization designated by |
2525 | // the template-name and template arguments corresponding to the |
2526 | // template parameters obtained from the class template. |
2527 | // |
2528 | // We use the injected-class-name type of the primary template instead. |
2529 | // This has the convenient property that it is different from any type that |
2530 | // the user can write in a deduction-guide (because they cannot enter the |
2531 | // context of the template), so implicit deduction guides can never collide |
2532 | // with explicit ones. |
2533 | QualType ReturnType = DeducedType; |
2534 | TLB.pushTypeSpec(T: ReturnType).setNameLoc(Primary->getLocation()); |
2535 | |
2536 | // Resolving a wording defect, we also inherit the variadicness of the |
2537 | // constructor. |
2538 | FunctionProtoType::ExtProtoInfo EPI; |
2539 | EPI.Variadic = T->isVariadic(); |
2540 | EPI.HasTrailingReturn = true; |
2541 | |
2542 | QualType Result = SemaRef.BuildFunctionType( |
2543 | T: ReturnType, ParamTypes, Loc: TL.getBeginLoc(), Entity: DeductionGuideName, EPI); |
2544 | if (Result.isNull()) |
2545 | return QualType(); |
2546 | |
2547 | FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(T: Result); |
2548 | NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); |
2549 | NewTL.setLParenLoc(TL.getLParenLoc()); |
2550 | NewTL.setRParenLoc(TL.getRParenLoc()); |
2551 | NewTL.setExceptionSpecRange(SourceRange()); |
2552 | NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); |
2553 | for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I) |
2554 | NewTL.setParam(I, Params[I]); |
2555 | |
2556 | return Result; |
2557 | } |
2558 | |
2559 | ParmVarDecl *transformFunctionTypeParam( |
2560 | ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args, |
2561 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { |
2562 | TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); |
2563 | TypeSourceInfo *NewDI; |
2564 | if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { |
2565 | // Expand out the one and only element in each inner pack. |
2566 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); |
2567 | NewDI = |
2568 | SemaRef.SubstType(PackTL.getPatternLoc(), Args, |
2569 | OldParam->getLocation(), OldParam->getDeclName()); |
2570 | if (!NewDI) return nullptr; |
2571 | NewDI = |
2572 | SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(), |
2573 | PackTL.getTypePtr()->getNumExpansions()); |
2574 | } else |
2575 | NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(), |
2576 | OldParam->getDeclName()); |
2577 | if (!NewDI) |
2578 | return nullptr; |
2579 | |
2580 | // Extract the type. This (for instance) replaces references to typedef |
2581 | // members of the current instantiations with the definitions of those |
2582 | // typedefs, avoiding triggering instantiation of the deduced type during |
2583 | // deduction. |
2584 | NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs) |
2585 | .transform(TSI: NewDI); |
2586 | |
2587 | // Resolving a wording defect, we also inherit default arguments from the |
2588 | // constructor. |
2589 | ExprResult NewDefArg; |
2590 | if (OldParam->hasDefaultArg()) { |
2591 | // We don't care what the value is (we won't use it); just create a |
2592 | // placeholder to indicate there is a default argument. |
2593 | QualType ParamTy = NewDI->getType(); |
2594 | NewDefArg = new (SemaRef.Context) |
2595 | OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(), |
2596 | ParamTy.getNonLValueExprType(Context: SemaRef.Context), |
2597 | ParamTy->isLValueReferenceType() ? VK_LValue |
2598 | : ParamTy->isRValueReferenceType() ? VK_XValue |
2599 | : VK_PRValue); |
2600 | } |
2601 | // Handle arrays and functions decay. |
2602 | auto NewType = NewDI->getType(); |
2603 | if (NewType->isArrayType() || NewType->isFunctionType()) |
2604 | NewType = SemaRef.Context.getDecayedType(T: NewType); |
2605 | |
2606 | ParmVarDecl *NewParam = ParmVarDecl::Create( |
2607 | C&: SemaRef.Context, DC, StartLoc: OldParam->getInnerLocStart(), |
2608 | IdLoc: OldParam->getLocation(), Id: OldParam->getIdentifier(), T: NewType, TInfo: NewDI, |
2609 | S: OldParam->getStorageClass(), DefArg: NewDefArg.get()); |
2610 | NewParam->setScopeInfo(scopeDepth: OldParam->getFunctionScopeDepth(), |
2611 | parameterIndex: OldParam->getFunctionScopeIndex()); |
2612 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); |
2613 | return NewParam; |
2614 | } |
2615 | |
2616 | FunctionTemplateDecl *buildDeductionGuide( |
2617 | TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor, |
2618 | ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart, |
2619 | SourceLocation Loc, SourceLocation LocEnd, |
2620 | llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) { |
2621 | DeclarationNameInfo Name(DeductionGuideName, Loc); |
2622 | ArrayRef<ParmVarDecl *> Params = |
2623 | TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(); |
2624 | |
2625 | // Build the implicit deduction guide template. |
2626 | auto *Guide = |
2627 | CXXDeductionGuideDecl::Create(C&: SemaRef.Context, DC, StartLoc: LocStart, ES, NameInfo: Name, |
2628 | T: TInfo->getType(), TInfo, EndLocation: LocEnd, Ctor); |
2629 | Guide->setImplicit(); |
2630 | Guide->setParams(Params); |
2631 | |
2632 | for (auto *Param : Params) |
2633 | Param->setDeclContext(Guide); |
2634 | for (auto *TD : MaterializedTypedefs) |
2635 | TD->setDeclContext(Guide); |
2636 | |
2637 | auto *GuideTemplate = FunctionTemplateDecl::Create( |
2638 | SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide); |
2639 | GuideTemplate->setImplicit(); |
2640 | Guide->setDescribedFunctionTemplate(GuideTemplate); |
2641 | |
2642 | if (isa<CXXRecordDecl>(Val: DC)) { |
2643 | Guide->setAccess(AS_public); |
2644 | GuideTemplate->setAccess(AS_public); |
2645 | } |
2646 | |
2647 | DC->addDecl(D: GuideTemplate); |
2648 | return GuideTemplate; |
2649 | } |
2650 | }; |
2651 | } |
2652 | |
2653 | FunctionTemplateDecl *Sema::DeclareImplicitDeductionGuideFromInitList( |
2654 | TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes, |
2655 | SourceLocation Loc) { |
2656 | if (CXXRecordDecl *DefRecord = |
2657 | cast<CXXRecordDecl>(Val: Template->getTemplatedDecl())->getDefinition()) { |
2658 | if (TemplateDecl *DescribedTemplate = |
2659 | DefRecord->getDescribedClassTemplate()) |
2660 | Template = DescribedTemplate; |
2661 | } |
2662 | |
2663 | DeclContext *DC = Template->getDeclContext(); |
2664 | if (DC->isDependentContext()) |
2665 | return nullptr; |
2666 | |
2667 | ConvertConstructorToDeductionGuideTransform Transform( |
2668 | *this, cast<ClassTemplateDecl>(Val: Template)); |
2669 | if (!isCompleteType(Loc, T: Transform.DeducedType)) |
2670 | return nullptr; |
2671 | |
2672 | // In case we were expanding a pack when we attempted to declare deduction |
2673 | // guides, turn off pack expansion for everything we're about to do. |
2674 | ArgumentPackSubstitutionIndexRAII SubstIndex(*this, |
2675 | /*NewSubstitutionIndex=*/-1); |
2676 | // Create a template instantiation record to track the "instantiation" of |
2677 | // constructors into deduction guides. |
2678 | InstantiatingTemplate BuildingDeductionGuides( |
2679 | *this, Loc, Template, |
2680 | Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{}); |
2681 | if (BuildingDeductionGuides.isInvalid()) |
2682 | return nullptr; |
2683 | |
2684 | ClassTemplateDecl *Pattern = |
2685 | Transform.NestedPattern ? Transform.NestedPattern : Transform.Template; |
2686 | ContextRAII SavedContext(*this, Pattern->getTemplatedDecl()); |
2687 | |
2688 | auto *DG = cast<FunctionTemplateDecl>( |
2689 | Val: Transform.buildSimpleDeductionGuide(ParamTypes)); |
2690 | SavedContext.pop(); |
2691 | return DG; |
2692 | } |
2693 | |
2694 | void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template, |
2695 | SourceLocation Loc) { |
2696 | if (CXXRecordDecl *DefRecord = |
2697 | cast<CXXRecordDecl>(Val: Template->getTemplatedDecl())->getDefinition()) { |
2698 | if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate()) |
2699 | Template = DescribedTemplate; |
2700 | } |
2701 | |
2702 | DeclContext *DC = Template->getDeclContext(); |
2703 | if (DC->isDependentContext()) |
2704 | return; |
2705 | |
2706 | ConvertConstructorToDeductionGuideTransform Transform( |
2707 | *this, cast<ClassTemplateDecl>(Val: Template)); |
2708 | if (!isCompleteType(Loc, T: Transform.DeducedType)) |
2709 | return; |
2710 | |
2711 | // Check whether we've already declared deduction guides for this template. |
2712 | // FIXME: Consider storing a flag on the template to indicate this. |
2713 | auto Existing = DC->lookup(Name: Transform.DeductionGuideName); |
2714 | for (auto *D : Existing) |
2715 | if (D->isImplicit()) |
2716 | return; |
2717 | |
2718 | // In case we were expanding a pack when we attempted to declare deduction |
2719 | // guides, turn off pack expansion for everything we're about to do. |
2720 | ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); |
2721 | // Create a template instantiation record to track the "instantiation" of |
2722 | // constructors into deduction guides. |
2723 | InstantiatingTemplate BuildingDeductionGuides( |
2724 | *this, Loc, Template, |
2725 | Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{}); |
2726 | if (BuildingDeductionGuides.isInvalid()) |
2727 | return; |
2728 | |
2729 | // Convert declared constructors into deduction guide templates. |
2730 | // FIXME: Skip constructors for which deduction must necessarily fail (those |
2731 | // for which some class template parameter without a default argument never |
2732 | // appears in a deduced context). |
2733 | ClassTemplateDecl *Pattern = |
2734 | Transform.NestedPattern ? Transform.NestedPattern : Transform.Template; |
2735 | ContextRAII SavedContext(*this, Pattern->getTemplatedDecl()); |
2736 | llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors; |
2737 | bool AddedAny = false; |
2738 | for (NamedDecl *D : LookupConstructors(Class: Pattern->getTemplatedDecl())) { |
2739 | D = D->getUnderlyingDecl(); |
2740 | if (D->isInvalidDecl() || D->isImplicit()) |
2741 | continue; |
2742 | |
2743 | D = cast<NamedDecl>(D->getCanonicalDecl()); |
2744 | |
2745 | // Within C++20 modules, we may have multiple same constructors in |
2746 | // multiple same RecordDecls. And it doesn't make sense to create |
2747 | // duplicated deduction guides for the duplicated constructors. |
2748 | if (ProcessedCtors.count(Ptr: D)) |
2749 | continue; |
2750 | |
2751 | auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D); |
2752 | auto *CD = |
2753 | dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D); |
2754 | // Class-scope explicit specializations (MS extension) do not result in |
2755 | // deduction guides. |
2756 | if (!CD || (!FTD && CD->isFunctionTemplateSpecialization())) |
2757 | continue; |
2758 | |
2759 | // Cannot make a deduction guide when unparsed arguments are present. |
2760 | if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) { |
2761 | return !P || P->hasUnparsedDefaultArg(); |
2762 | })) |
2763 | continue; |
2764 | |
2765 | ProcessedCtors.insert(Ptr: D); |
2766 | Transform.transformConstructor(FTD, CD: CD); |
2767 | AddedAny = true; |
2768 | } |
2769 | |
2770 | // C++17 [over.match.class.deduct] |
2771 | // -- If C is not defined or does not declare any constructors, an |
2772 | // additional function template derived as above from a hypothetical |
2773 | // constructor C(). |
2774 | if (!AddedAny) |
2775 | Transform.buildSimpleDeductionGuide(ParamTypes: std::nullopt); |
2776 | |
2777 | // -- An additional function template derived as above from a hypothetical |
2778 | // constructor C(C), called the copy deduction candidate. |
2779 | cast<CXXDeductionGuideDecl>( |
2780 | cast<FunctionTemplateDecl>( |
2781 | Transform.buildSimpleDeductionGuide(ParamTypes: Transform.DeducedType)) |
2782 | ->getTemplatedDecl()) |
2783 | ->setDeductionCandidateKind(DeductionCandidate::Copy); |
2784 | |
2785 | SavedContext.pop(); |
2786 | } |
2787 | |
2788 | /// Diagnose the presence of a default template argument on a |
2789 | /// template parameter, which is ill-formed in certain contexts. |
2790 | /// |
2791 | /// \returns true if the default template argument should be dropped. |
2792 | static bool DiagnoseDefaultTemplateArgument(Sema &S, |
2793 | Sema::TemplateParamListContext TPC, |
2794 | SourceLocation ParamLoc, |
2795 | SourceRange DefArgRange) { |
2796 | switch (TPC) { |
2797 | case Sema::TPC_ClassTemplate: |
2798 | case Sema::TPC_VarTemplate: |
2799 | case Sema::TPC_TypeAliasTemplate: |
2800 | return false; |
2801 | |
2802 | case Sema::TPC_FunctionTemplate: |
2803 | case Sema::TPC_FriendFunctionTemplateDefinition: |
2804 | // C++ [temp.param]p9: |
2805 | // A default template-argument shall not be specified in a |
2806 | // function template declaration or a function template |
2807 | // definition [...] |
2808 | // If a friend function template declaration specifies a default |
2809 | // template-argument, that declaration shall be a definition and shall be |
2810 | // the only declaration of the function template in the translation unit. |
2811 | // (C++98/03 doesn't have this wording; see DR226). |
2812 | S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? |
2813 | diag::warn_cxx98_compat_template_parameter_default_in_function_template |
2814 | : diag::ext_template_parameter_default_in_function_template) |
2815 | << DefArgRange; |
2816 | return false; |
2817 | |
2818 | case Sema::TPC_ClassTemplateMember: |
2819 | // C++0x [temp.param]p9: |
2820 | // A default template-argument shall not be specified in the |
2821 | // template-parameter-lists of the definition of a member of a |
2822 | // class template that appears outside of the member's class. |
2823 | S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) |
2824 | << DefArgRange; |
2825 | return true; |
2826 | |
2827 | case Sema::TPC_FriendClassTemplate: |
2828 | case Sema::TPC_FriendFunctionTemplate: |
2829 | // C++ [temp.param]p9: |
2830 | // A default template-argument shall not be specified in a |
2831 | // friend template declaration. |
2832 | S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) |
2833 | << DefArgRange; |
2834 | return true; |
2835 | |
2836 | // FIXME: C++0x [temp.param]p9 allows default template-arguments |
2837 | // for friend function templates if there is only a single |
2838 | // declaration (and it is a definition). Strange! |
2839 | } |
2840 | |
2841 | llvm_unreachable("Invalid TemplateParamListContext!" ); |
2842 | } |
2843 | |
2844 | /// Check for unexpanded parameter packs within the template parameters |
2845 | /// of a template template parameter, recursively. |
2846 | static bool DiagnoseUnexpandedParameterPacks(Sema &S, |
2847 | TemplateTemplateParmDecl *TTP) { |
2848 | // A template template parameter which is a parameter pack is also a pack |
2849 | // expansion. |
2850 | if (TTP->isParameterPack()) |
2851 | return false; |
2852 | |
2853 | TemplateParameterList *Params = TTP->getTemplateParameters(); |
2854 | for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
2855 | NamedDecl *P = Params->getParam(Idx: I); |
2856 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) { |
2857 | if (!TTP->isParameterPack()) |
2858 | if (const TypeConstraint *TC = TTP->getTypeConstraint()) |
2859 | if (TC->hasExplicitTemplateArgs()) |
2860 | for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) |
2861 | if (S.DiagnoseUnexpandedParameterPack(ArgLoc, |
2862 | Sema::UPPC_TypeConstraint)) |
2863 | return true; |
2864 | continue; |
2865 | } |
2866 | |
2867 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) { |
2868 | if (!NTTP->isParameterPack() && |
2869 | S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), |
2870 | NTTP->getTypeSourceInfo(), |
2871 | Sema::UPPC_NonTypeTemplateParameterType)) |
2872 | return true; |
2873 | |
2874 | continue; |
2875 | } |
2876 | |
2877 | if (TemplateTemplateParmDecl *InnerTTP |
2878 | = dyn_cast<TemplateTemplateParmDecl>(Val: P)) |
2879 | if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP)) |
2880 | return true; |
2881 | } |
2882 | |
2883 | return false; |
2884 | } |
2885 | |
2886 | /// Checks the validity of a template parameter list, possibly |
2887 | /// considering the template parameter list from a previous |
2888 | /// declaration. |
2889 | /// |
2890 | /// If an "old" template parameter list is provided, it must be |
2891 | /// equivalent (per TemplateParameterListsAreEqual) to the "new" |
2892 | /// template parameter list. |
2893 | /// |
2894 | /// \param NewParams Template parameter list for a new template |
2895 | /// declaration. This template parameter list will be updated with any |
2896 | /// default arguments that are carried through from the previous |
2897 | /// template parameter list. |
2898 | /// |
2899 | /// \param OldParams If provided, template parameter list from a |
2900 | /// previous declaration of the same template. Default template |
2901 | /// arguments will be merged from the old template parameter list to |
2902 | /// the new template parameter list. |
2903 | /// |
2904 | /// \param TPC Describes the context in which we are checking the given |
2905 | /// template parameter list. |
2906 | /// |
2907 | /// \param SkipBody If we might have already made a prior merged definition |
2908 | /// of this template visible, the corresponding body-skipping information. |
2909 | /// Default argument redefinition is not an error when skipping such a body, |
2910 | /// because (under the ODR) we can assume the default arguments are the same |
2911 | /// as the prior merged definition. |
2912 | /// |
2913 | /// \returns true if an error occurred, false otherwise. |
2914 | bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, |
2915 | TemplateParameterList *OldParams, |
2916 | TemplateParamListContext TPC, |
2917 | SkipBodyInfo *SkipBody) { |
2918 | bool Invalid = false; |
2919 | |
2920 | // C++ [temp.param]p10: |
2921 | // The set of default template-arguments available for use with a |
2922 | // template declaration or definition is obtained by merging the |
2923 | // default arguments from the definition (if in scope) and all |
2924 | // declarations in scope in the same way default function |
2925 | // arguments are (8.3.6). |
2926 | bool SawDefaultArgument = false; |
2927 | SourceLocation PreviousDefaultArgLoc; |
2928 | |
2929 | // Dummy initialization to avoid warnings. |
2930 | TemplateParameterList::iterator OldParam = NewParams->end(); |
2931 | if (OldParams) |
2932 | OldParam = OldParams->begin(); |
2933 | |
2934 | bool RemoveDefaultArguments = false; |
2935 | for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
2936 | NewParamEnd = NewParams->end(); |
2937 | NewParam != NewParamEnd; ++NewParam) { |
2938 | // Whether we've seen a duplicate default argument in the same translation |
2939 | // unit. |
2940 | bool RedundantDefaultArg = false; |
2941 | // Whether we've found inconsis inconsitent default arguments in different |
2942 | // translation unit. |
2943 | bool InconsistentDefaultArg = false; |
2944 | // The name of the module which contains the inconsistent default argument. |
2945 | std::string PrevModuleName; |
2946 | |
2947 | SourceLocation OldDefaultLoc; |
2948 | SourceLocation NewDefaultLoc; |
2949 | |
2950 | // Variable used to diagnose missing default arguments |
2951 | bool MissingDefaultArg = false; |
2952 | |
2953 | // Variable used to diagnose non-final parameter packs |
2954 | bool SawParameterPack = false; |
2955 | |
2956 | if (TemplateTypeParmDecl *NewTypeParm |
2957 | = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) { |
2958 | // Check the presence of a default argument here. |
2959 | if (NewTypeParm->hasDefaultArgument() && |
2960 | DiagnoseDefaultTemplateArgument(*this, TPC, |
2961 | NewTypeParm->getLocation(), |
2962 | NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() |
2963 | .getSourceRange())) |
2964 | NewTypeParm->removeDefaultArgument(); |
2965 | |
2966 | // Merge default arguments for template type parameters. |
2967 | TemplateTypeParmDecl *OldTypeParm |
2968 | = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr; |
2969 | if (NewTypeParm->isParameterPack()) { |
2970 | assert(!NewTypeParm->hasDefaultArgument() && |
2971 | "Parameter packs can't have a default argument!" ); |
2972 | SawParameterPack = true; |
2973 | } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) && |
2974 | NewTypeParm->hasDefaultArgument() && |
2975 | (!SkipBody || !SkipBody->ShouldSkip)) { |
2976 | OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); |
2977 | NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); |
2978 | SawDefaultArgument = true; |
2979 | |
2980 | if (!OldTypeParm->getOwningModule()) |
2981 | RedundantDefaultArg = true; |
2982 | else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm, |
2983 | NewTypeParm)) { |
2984 | InconsistentDefaultArg = true; |
2985 | PrevModuleName = |
2986 | OldTypeParm->getImportedOwningModule()->getFullModuleName(); |
2987 | } |
2988 | PreviousDefaultArgLoc = NewDefaultLoc; |
2989 | } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { |
2990 | // Merge the default argument from the old declaration to the |
2991 | // new declaration. |
2992 | NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm); |
2993 | PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); |
2994 | } else if (NewTypeParm->hasDefaultArgument()) { |
2995 | SawDefaultArgument = true; |
2996 | PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); |
2997 | } else if (SawDefaultArgument) |
2998 | MissingDefaultArg = true; |
2999 | } else if (NonTypeTemplateParmDecl *NewNonTypeParm |
3000 | = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) { |
3001 | // Check for unexpanded parameter packs. |
3002 | if (!NewNonTypeParm->isParameterPack() && |
3003 | DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), |
3004 | NewNonTypeParm->getTypeSourceInfo(), |
3005 | UPPC_NonTypeTemplateParameterType)) { |
3006 | Invalid = true; |
3007 | continue; |
3008 | } |
3009 | |
3010 | // Check the presence of a default argument here. |
3011 | if (NewNonTypeParm->hasDefaultArgument() && |
3012 | DiagnoseDefaultTemplateArgument(*this, TPC, |
3013 | NewNonTypeParm->getLocation(), |
3014 | NewNonTypeParm->getDefaultArgument()->getSourceRange())) { |
3015 | NewNonTypeParm->removeDefaultArgument(); |
3016 | } |
3017 | |
3018 | // Merge default arguments for non-type template parameters |
3019 | NonTypeTemplateParmDecl *OldNonTypeParm |
3020 | = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr; |
3021 | if (NewNonTypeParm->isParameterPack()) { |
3022 | assert(!NewNonTypeParm->hasDefaultArgument() && |
3023 | "Parameter packs can't have a default argument!" ); |
3024 | if (!NewNonTypeParm->isPackExpansion()) |
3025 | SawParameterPack = true; |
3026 | } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) && |
3027 | NewNonTypeParm->hasDefaultArgument() && |
3028 | (!SkipBody || !SkipBody->ShouldSkip)) { |
3029 | OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
3030 | NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
3031 | SawDefaultArgument = true; |
3032 | if (!OldNonTypeParm->getOwningModule()) |
3033 | RedundantDefaultArg = true; |
3034 | else if (!getASTContext().isSameDefaultTemplateArgument( |
3035 | OldNonTypeParm, NewNonTypeParm)) { |
3036 | InconsistentDefaultArg = true; |
3037 | PrevModuleName = |
3038 | OldNonTypeParm->getImportedOwningModule()->getFullModuleName(); |
3039 | } |
3040 | PreviousDefaultArgLoc = NewDefaultLoc; |
3041 | } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { |
3042 | // Merge the default argument from the old declaration to the |
3043 | // new declaration. |
3044 | NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm); |
3045 | PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
3046 | } else if (NewNonTypeParm->hasDefaultArgument()) { |
3047 | SawDefaultArgument = true; |
3048 | PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
3049 | } else if (SawDefaultArgument) |
3050 | MissingDefaultArg = true; |
3051 | } else { |
3052 | TemplateTemplateParmDecl *NewTemplateParm |
3053 | = cast<TemplateTemplateParmDecl>(Val: *NewParam); |
3054 | |
3055 | // Check for unexpanded parameter packs, recursively. |
3056 | if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) { |
3057 | Invalid = true; |
3058 | continue; |
3059 | } |
3060 | |
3061 | // Check the presence of a default argument here. |
3062 | if (NewTemplateParm->hasDefaultArgument() && |
3063 | DiagnoseDefaultTemplateArgument(*this, TPC, |
3064 | NewTemplateParm->getLocation(), |
3065 | NewTemplateParm->getDefaultArgument().getSourceRange())) |
3066 | NewTemplateParm->removeDefaultArgument(); |
3067 | |
3068 | // Merge default arguments for template template parameters |
3069 | TemplateTemplateParmDecl *OldTemplateParm |
3070 | = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr; |
3071 | if (NewTemplateParm->isParameterPack()) { |
3072 | assert(!NewTemplateParm->hasDefaultArgument() && |
3073 | "Parameter packs can't have a default argument!" ); |
3074 | if (!NewTemplateParm->isPackExpansion()) |
3075 | SawParameterPack = true; |
3076 | } else if (OldTemplateParm && |
3077 | hasVisibleDefaultArgument(OldTemplateParm) && |
3078 | NewTemplateParm->hasDefaultArgument() && |
3079 | (!SkipBody || !SkipBody->ShouldSkip)) { |
3080 | OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); |
3081 | NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); |
3082 | SawDefaultArgument = true; |
3083 | if (!OldTemplateParm->getOwningModule()) |
3084 | RedundantDefaultArg = true; |
3085 | else if (!getASTContext().isSameDefaultTemplateArgument( |
3086 | OldTemplateParm, NewTemplateParm)) { |
3087 | InconsistentDefaultArg = true; |
3088 | PrevModuleName = |
3089 | OldTemplateParm->getImportedOwningModule()->getFullModuleName(); |
3090 | } |
3091 | PreviousDefaultArgLoc = NewDefaultLoc; |
3092 | } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { |
3093 | // Merge the default argument from the old declaration to the |
3094 | // new declaration. |
3095 | NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm); |
3096 | PreviousDefaultArgLoc |
3097 | = OldTemplateParm->getDefaultArgument().getLocation(); |
3098 | } else if (NewTemplateParm->hasDefaultArgument()) { |
3099 | SawDefaultArgument = true; |
3100 | PreviousDefaultArgLoc |
3101 | = NewTemplateParm->getDefaultArgument().getLocation(); |
3102 | } else if (SawDefaultArgument) |
3103 | MissingDefaultArg = true; |
3104 | } |
3105 | |
3106 | // C++11 [temp.param]p11: |
3107 | // If a template parameter of a primary class template or alias template |
3108 | // is a template parameter pack, it shall be the last template parameter. |
3109 | if (SawParameterPack && (NewParam + 1) != NewParamEnd && |
3110 | (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || |
3111 | TPC == TPC_TypeAliasTemplate)) { |
3112 | Diag((*NewParam)->getLocation(), |
3113 | diag::err_template_param_pack_must_be_last_template_parameter); |
3114 | Invalid = true; |
3115 | } |
3116 | |
3117 | // [basic.def.odr]/13: |
3118 | // There can be more than one definition of a |
3119 | // ... |
3120 | // default template argument |
3121 | // ... |
3122 | // in a program provided that each definition appears in a different |
3123 | // translation unit and the definitions satisfy the [same-meaning |
3124 | // criteria of the ODR]. |
3125 | // |
3126 | // Simply, the design of modules allows the definition of template default |
3127 | // argument to be repeated across translation unit. Note that the ODR is |
3128 | // checked elsewhere. But it is still not allowed to repeat template default |
3129 | // argument in the same translation unit. |
3130 | if (RedundantDefaultArg) { |
3131 | Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); |
3132 | Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); |
3133 | Invalid = true; |
3134 | } else if (InconsistentDefaultArg) { |
3135 | // We could only diagnose about the case that the OldParam is imported. |
3136 | // The case NewParam is imported should be handled in ASTReader. |
3137 | Diag(NewDefaultLoc, |
3138 | diag::err_template_param_default_arg_inconsistent_redefinition); |
3139 | Diag(OldDefaultLoc, |
3140 | diag::note_template_param_prev_default_arg_in_other_module) |
3141 | << PrevModuleName; |
3142 | Invalid = true; |
3143 | } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { |
3144 | // C++ [temp.param]p11: |
3145 | // If a template-parameter of a class template has a default |
3146 | // template-argument, each subsequent template-parameter shall either |
3147 | // have a default template-argument supplied or be a template parameter |
3148 | // pack. |
3149 | Diag((*NewParam)->getLocation(), |
3150 | diag::err_template_param_default_arg_missing); |
3151 | Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); |
3152 | Invalid = true; |
3153 | RemoveDefaultArguments = true; |
3154 | } |
3155 | |
3156 | // If we have an old template parameter list that we're merging |
3157 | // in, move on to the next parameter. |
3158 | if (OldParams) |
3159 | ++OldParam; |
3160 | } |
3161 | |
3162 | // We were missing some default arguments at the end of the list, so remove |
3163 | // all of the default arguments. |
3164 | if (RemoveDefaultArguments) { |
3165 | for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
3166 | NewParamEnd = NewParams->end(); |
3167 | NewParam != NewParamEnd; ++NewParam) { |
3168 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) |
3169 | TTP->removeDefaultArgument(); |
3170 | else if (NonTypeTemplateParmDecl *NTTP |
3171 | = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) |
3172 | NTTP->removeDefaultArgument(); |
3173 | else |
3174 | cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument(); |
3175 | } |
3176 | } |
3177 | |
3178 | return Invalid; |
3179 | } |
3180 | |
3181 | namespace { |
3182 | |
3183 | /// A class which looks for a use of a certain level of template |
3184 | /// parameter. |
3185 | struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { |
3186 | typedef RecursiveASTVisitor<DependencyChecker> super; |
3187 | |
3188 | unsigned Depth; |
3189 | |
3190 | // Whether we're looking for a use of a template parameter that makes the |
3191 | // overall construct type-dependent / a dependent type. This is strictly |
3192 | // best-effort for now; we may fail to match at all for a dependent type |
3193 | // in some cases if this is set. |
3194 | bool IgnoreNonTypeDependent; |
3195 | |
3196 | bool Match; |
3197 | SourceLocation MatchLoc; |
3198 | |
3199 | DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent) |
3200 | : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent), |
3201 | Match(false) {} |
3202 | |
3203 | DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent) |
3204 | : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) { |
3205 | NamedDecl *ND = Params->getParam(Idx: 0); |
3206 | if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) { |
3207 | Depth = PD->getDepth(); |
3208 | } else if (NonTypeTemplateParmDecl *PD = |
3209 | dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) { |
3210 | Depth = PD->getDepth(); |
3211 | } else { |
3212 | Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth(); |
3213 | } |
3214 | } |
3215 | |
3216 | bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { |
3217 | if (ParmDepth >= Depth) { |
3218 | Match = true; |
3219 | MatchLoc = Loc; |
3220 | return true; |
3221 | } |
3222 | return false; |
3223 | } |
3224 | |
3225 | bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) { |
3226 | // Prune out non-type-dependent expressions if requested. This can |
3227 | // sometimes result in us failing to find a template parameter reference |
3228 | // (if a value-dependent expression creates a dependent type), but this |
3229 | // mode is best-effort only. |
3230 | if (auto *E = dyn_cast_or_null<Expr>(Val: S)) |
3231 | if (IgnoreNonTypeDependent && !E->isTypeDependent()) |
3232 | return true; |
3233 | return super::TraverseStmt(S, Queue: Q); |
3234 | } |
3235 | |
3236 | bool TraverseTypeLoc(TypeLoc TL) { |
3237 | if (IgnoreNonTypeDependent && !TL.isNull() && |
3238 | !TL.getType()->isDependentType()) |
3239 | return true; |
3240 | return super::TraverseTypeLoc(TL); |
3241 | } |
3242 | |
3243 | bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { |
3244 | return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc()); |
3245 | } |
3246 | |
3247 | bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { |
3248 | // For a best-effort search, keep looking until we find a location. |
3249 | return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth()); |
3250 | } |
3251 | |
3252 | bool TraverseTemplateName(TemplateName N) { |
3253 | if (TemplateTemplateParmDecl *PD = |
3254 | dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl())) |
3255 | if (Matches(ParmDepth: PD->getDepth())) |
3256 | return false; |
3257 | return super::TraverseTemplateName(Template: N); |
3258 | } |
3259 | |
3260 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
3261 | if (NonTypeTemplateParmDecl *PD = |
3262 | dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl())) |
3263 | if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc())) |
3264 | return false; |
3265 | return super::VisitDeclRefExpr(E); |
3266 | } |
3267 | |
3268 | bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { |
3269 | return TraverseType(T: T->getReplacementType()); |
3270 | } |
3271 | |
3272 | bool |
3273 | VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { |
3274 | return TraverseTemplateArgument(Arg: T->getArgumentPack()); |
3275 | } |
3276 | |
3277 | bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { |
3278 | return TraverseType(T: T->getInjectedSpecializationType()); |
3279 | } |
3280 | }; |
3281 | } // end anonymous namespace |
3282 | |
3283 | /// Determines whether a given type depends on the given parameter |
3284 | /// list. |
3285 | static bool |
3286 | DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { |
3287 | if (!Params->size()) |
3288 | return false; |
3289 | |
3290 | DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false); |
3291 | Checker.TraverseType(T); |
3292 | return Checker.Match; |
3293 | } |
3294 | |
3295 | // Find the source range corresponding to the named type in the given |
3296 | // nested-name-specifier, if any. |
3297 | static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, |
3298 | QualType T, |
3299 | const CXXScopeSpec &SS) { |
3300 | NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); |
3301 | while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { |
3302 | if (const Type *CurType = NNS->getAsType()) { |
3303 | if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(CurType, 0))) |
3304 | return NNSLoc.getTypeLoc().getSourceRange(); |
3305 | } else |
3306 | break; |
3307 | |
3308 | NNSLoc = NNSLoc.getPrefix(); |
3309 | } |
3310 | |
3311 | return SourceRange(); |
3312 | } |
3313 | |
3314 | /// Match the given template parameter lists to the given scope |
3315 | /// specifier, returning the template parameter list that applies to the |
3316 | /// name. |
3317 | /// |
3318 | /// \param DeclStartLoc the start of the declaration that has a scope |
3319 | /// specifier or a template parameter list. |
3320 | /// |
3321 | /// \param DeclLoc The location of the declaration itself. |
3322 | /// |
3323 | /// \param SS the scope specifier that will be matched to the given template |
3324 | /// parameter lists. This scope specifier precedes a qualified name that is |
3325 | /// being declared. |
3326 | /// |
3327 | /// \param TemplateId The template-id following the scope specifier, if there |
3328 | /// is one. Used to check for a missing 'template<>'. |
3329 | /// |
3330 | /// \param ParamLists the template parameter lists, from the outermost to the |
3331 | /// innermost template parameter lists. |
3332 | /// |
3333 | /// \param IsFriend Whether to apply the slightly different rules for |
3334 | /// matching template parameters to scope specifiers in friend |
3335 | /// declarations. |
3336 | /// |
3337 | /// \param IsMemberSpecialization will be set true if the scope specifier |
3338 | /// denotes a fully-specialized type, and therefore this is a declaration of |
3339 | /// a member specialization. |
3340 | /// |
3341 | /// \returns the template parameter list, if any, that corresponds to the |
3342 | /// name that is preceded by the scope specifier @p SS. This template |
3343 | /// parameter list may have template parameters (if we're declaring a |
3344 | /// template) or may have no template parameters (if we're declaring a |
3345 | /// template specialization), or may be NULL (if what we're declaring isn't |
3346 | /// itself a template). |
3347 | TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( |
3348 | SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, |
3349 | TemplateIdAnnotation *TemplateId, |
3350 | ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, |
3351 | bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) { |
3352 | IsMemberSpecialization = false; |
3353 | Invalid = false; |
3354 | |
3355 | // The sequence of nested types to which we will match up the template |
3356 | // parameter lists. We first build this list by starting with the type named |
3357 | // by the nested-name-specifier and walking out until we run out of types. |
3358 | SmallVector<QualType, 4> NestedTypes; |
3359 | QualType T; |
3360 | if (SS.getScopeRep()) { |
3361 | if (CXXRecordDecl *Record |
3362 | = dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true))) |
3363 | T = Context.getTypeDeclType(Record); |
3364 | else |
3365 | T = QualType(SS.getScopeRep()->getAsType(), 0); |
3366 | } |
3367 | |
3368 | // If we found an explicit specialization that prevents us from needing |
3369 | // 'template<>' headers, this will be set to the location of that |
3370 | // explicit specialization. |
3371 | SourceLocation ExplicitSpecLoc; |
3372 | |
3373 | while (!T.isNull()) { |
3374 | NestedTypes.push_back(Elt: T); |
3375 | |
3376 | // Retrieve the parent of a record type. |
3377 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
3378 | // If this type is an explicit specialization, we're done. |
3379 | if (ClassTemplateSpecializationDecl *Spec |
3380 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) { |
3381 | if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) && |
3382 | Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { |
3383 | ExplicitSpecLoc = Spec->getLocation(); |
3384 | break; |
3385 | } |
3386 | } else if (Record->getTemplateSpecializationKind() |
3387 | == TSK_ExplicitSpecialization) { |
3388 | ExplicitSpecLoc = Record->getLocation(); |
3389 | break; |
3390 | } |
3391 | |
3392 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) |
3393 | T = Context.getTypeDeclType(Decl: Parent); |
3394 | else |
3395 | T = QualType(); |
3396 | continue; |
3397 | } |
3398 | |
3399 | if (const TemplateSpecializationType *TST |
3400 | = T->getAs<TemplateSpecializationType>()) { |
3401 | if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
3402 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) |
3403 | T = Context.getTypeDeclType(Decl: Parent); |
3404 | else |
3405 | T = QualType(); |
3406 | continue; |
3407 | } |
3408 | } |
3409 | |
3410 | // Look one step prior in a dependent template specialization type. |
3411 | if (const DependentTemplateSpecializationType *DependentTST |
3412 | = T->getAs<DependentTemplateSpecializationType>()) { |
3413 | if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) |
3414 | T = QualType(NNS->getAsType(), 0); |
3415 | else |
3416 | T = QualType(); |
3417 | continue; |
3418 | } |
3419 | |
3420 | // Look one step prior in a dependent name type. |
3421 | if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ |
3422 | if (NestedNameSpecifier *NNS = DependentName->getQualifier()) |
3423 | T = QualType(NNS->getAsType(), 0); |
3424 | else |
3425 | T = QualType(); |
3426 | continue; |
3427 | } |
3428 | |
3429 | // Retrieve the parent of an enumeration type. |
3430 | if (const EnumType *EnumT = T->getAs<EnumType>()) { |
3431 | // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization |
3432 | // check here. |
3433 | EnumDecl *Enum = EnumT->getDecl(); |
3434 | |
3435 | // Get to the parent type. |
3436 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) |
3437 | T = Context.getTypeDeclType(Decl: Parent); |
3438 | else |
3439 | T = QualType(); |
3440 | continue; |
3441 | } |
3442 | |
3443 | T = QualType(); |
3444 | } |
3445 | // Reverse the nested types list, since we want to traverse from the outermost |
3446 | // to the innermost while checking template-parameter-lists. |
3447 | std::reverse(first: NestedTypes.begin(), last: NestedTypes.end()); |
3448 | |
3449 | // C++0x [temp.expl.spec]p17: |
3450 | // A member or a member template may be nested within many |
3451 | // enclosing class templates. In an explicit specialization for |
3452 | // such a member, the member declaration shall be preceded by a |
3453 | // template<> for each enclosing class template that is |
3454 | // explicitly specialized. |
3455 | bool SawNonEmptyTemplateParameterList = false; |
3456 | |
3457 | auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { |
3458 | if (SawNonEmptyTemplateParameterList) { |
3459 | if (!SuppressDiagnostic) |
3460 | Diag(DeclLoc, diag::err_specialize_member_of_template) |
3461 | << !Recovery << Range; |
3462 | Invalid = true; |
3463 | IsMemberSpecialization = false; |
3464 | return true; |
3465 | } |
3466 | |
3467 | return false; |
3468 | }; |
3469 | |
3470 | auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { |
3471 | // Check that we can have an explicit specialization here. |
3472 | if (CheckExplicitSpecialization(Range, true)) |
3473 | return true; |
3474 | |
3475 | // We don't have a template header, but we should. |
3476 | SourceLocation ExpectedTemplateLoc; |
3477 | if (!ParamLists.empty()) |
3478 | ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); |
3479 | else |
3480 | ExpectedTemplateLoc = DeclStartLoc; |
3481 | |
3482 | if (!SuppressDiagnostic) |
3483 | Diag(DeclLoc, diag::err_template_spec_needs_header) |
3484 | << Range |
3485 | << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> " ); |
3486 | return false; |
3487 | }; |
3488 | |
3489 | unsigned ParamIdx = 0; |
3490 | for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; |
3491 | ++TypeIdx) { |
3492 | T = NestedTypes[TypeIdx]; |
3493 | |
3494 | // Whether we expect a 'template<>' header. |
3495 | bool = false; |
3496 | |
3497 | // Whether we expect a template header with parameters. |
3498 | bool = false; |
3499 | |
3500 | // For a dependent type, the set of template parameters that we |
3501 | // expect to see. |
3502 | TemplateParameterList *ExpectedTemplateParams = nullptr; |
3503 | |
3504 | // C++0x [temp.expl.spec]p15: |
3505 | // A member or a member template may be nested within many enclosing |
3506 | // class templates. In an explicit specialization for such a member, the |
3507 | // member declaration shall be preceded by a template<> for each |
3508 | // enclosing class template that is explicitly specialized. |
3509 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
3510 | if (ClassTemplatePartialSpecializationDecl *Partial |
3511 | = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) { |
3512 | ExpectedTemplateParams = Partial->getTemplateParameters(); |
3513 | NeedNonemptyTemplateHeader = true; |
3514 | } else if (Record->isDependentType()) { |
3515 | if (Record->getDescribedClassTemplate()) { |
3516 | ExpectedTemplateParams = Record->getDescribedClassTemplate() |
3517 | ->getTemplateParameters(); |
3518 | NeedNonemptyTemplateHeader = true; |
3519 | } |
3520 | } else if (ClassTemplateSpecializationDecl *Spec |
3521 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) { |
3522 | // C++0x [temp.expl.spec]p4: |
3523 | // Members of an explicitly specialized class template are defined |
3524 | // in the same manner as members of normal classes, and not using |
3525 | // the template<> syntax. |
3526 | if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) |
3527 | NeedEmptyTemplateHeader = true; |
3528 | else |
3529 | continue; |
3530 | } else if (Record->getTemplateSpecializationKind()) { |
3531 | if (Record->getTemplateSpecializationKind() |
3532 | != TSK_ExplicitSpecialization && |
3533 | TypeIdx == NumTypes - 1) |
3534 | IsMemberSpecialization = true; |
3535 | |
3536 | continue; |
3537 | } |
3538 | } else if (const TemplateSpecializationType *TST |
3539 | = T->getAs<TemplateSpecializationType>()) { |
3540 | if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
3541 | ExpectedTemplateParams = Template->getTemplateParameters(); |
3542 | NeedNonemptyTemplateHeader = true; |
3543 | } |
3544 | } else if (T->getAs<DependentTemplateSpecializationType>()) { |
3545 | // FIXME: We actually could/should check the template arguments here |
3546 | // against the corresponding template parameter list. |
3547 | NeedNonemptyTemplateHeader = false; |
3548 | } |
3549 | |
3550 | // C++ [temp.expl.spec]p16: |
3551 | // In an explicit specialization declaration for a member of a class |
3552 | // template or a member template that ap- pears in namespace scope, the |
3553 | // member template and some of its enclosing class templates may remain |
3554 | // unspecialized, except that the declaration shall not explicitly |
3555 | // specialize a class member template if its en- closing class templates |
3556 | // are not explicitly specialized as well. |
3557 | if (ParamIdx < ParamLists.size()) { |
3558 | if (ParamLists[ParamIdx]->size() == 0) { |
3559 | if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
3560 | false)) |
3561 | return nullptr; |
3562 | } else |
3563 | SawNonEmptyTemplateParameterList = true; |
3564 | } |
3565 | |
3566 | if (NeedEmptyTemplateHeader) { |
3567 | // If we're on the last of the types, and we need a 'template<>' header |
3568 | // here, then it's a member specialization. |
3569 | if (TypeIdx == NumTypes - 1) |
3570 | IsMemberSpecialization = true; |
3571 | |
3572 | if (ParamIdx < ParamLists.size()) { |
3573 | if (ParamLists[ParamIdx]->size() > 0) { |
3574 | // The header has template parameters when it shouldn't. Complain. |
3575 | if (!SuppressDiagnostic) |
3576 | Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
3577 | diag::err_template_param_list_matches_nontemplate) |
3578 | << T |
3579 | << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), |
3580 | ParamLists[ParamIdx]->getRAngleLoc()) |
3581 | << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
3582 | Invalid = true; |
3583 | return nullptr; |
3584 | } |
3585 | |
3586 | // Consume this template header. |
3587 | ++ParamIdx; |
3588 | continue; |
3589 | } |
3590 | |
3591 | if (!IsFriend) |
3592 | if (DiagnoseMissingExplicitSpecialization( |
3593 | getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) |
3594 | return nullptr; |
3595 | |
3596 | continue; |
3597 | } |
3598 | |
3599 | if (NeedNonemptyTemplateHeader) { |
3600 | // In friend declarations we can have template-ids which don't |
3601 | // depend on the corresponding template parameter lists. But |
3602 | // assume that empty parameter lists are supposed to match this |
3603 | // template-id. |
3604 | if (IsFriend && T->isDependentType()) { |
3605 | if (ParamIdx < ParamLists.size() && |
3606 | DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx])) |
3607 | ExpectedTemplateParams = nullptr; |
3608 | else |
3609 | continue; |
3610 | } |
3611 | |
3612 | if (ParamIdx < ParamLists.size()) { |
3613 | // Check the template parameter list, if we can. |
3614 | if (ExpectedTemplateParams && |
3615 | !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx], |
3616 | Old: ExpectedTemplateParams, |
3617 | Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch)) |
3618 | Invalid = true; |
3619 | |
3620 | if (!Invalid && |
3621 | CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr, |
3622 | TPC: TPC_ClassTemplateMember)) |
3623 | Invalid = true; |
3624 | |
3625 | ++ParamIdx; |
3626 | continue; |
3627 | } |
3628 | |
3629 | if (!SuppressDiagnostic) |
3630 | Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) |
3631 | << T |
3632 | << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
3633 | Invalid = true; |
3634 | continue; |
3635 | } |
3636 | } |
3637 | |
3638 | // If there were at least as many template-ids as there were template |
3639 | // parameter lists, then there are no template parameter lists remaining for |
3640 | // the declaration itself. |
3641 | if (ParamIdx >= ParamLists.size()) { |
3642 | if (TemplateId && !IsFriend) { |
3643 | // We don't have a template header for the declaration itself, but we |
3644 | // should. |
3645 | DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, |
3646 | TemplateId->RAngleLoc)); |
3647 | |
3648 | // Fabricate an empty template parameter list for the invented header. |
3649 | return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(), |
3650 | LAngleLoc: SourceLocation(), Params: std::nullopt, |
3651 | RAngleLoc: SourceLocation(), RequiresClause: nullptr); |
3652 | } |
3653 | |
3654 | return nullptr; |
3655 | } |
3656 | |
3657 | // If there were too many template parameter lists, complain about that now. |
3658 | if (ParamIdx < ParamLists.size() - 1) { |
3659 | bool = false; |
3660 | bool = true; |
3661 | for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { |
3662 | if (ParamLists[I]->size() == 0) |
3663 | HasAnyExplicitSpecHeader = true; |
3664 | else |
3665 | AllExplicitSpecHeaders = false; |
3666 | } |
3667 | |
3668 | if (!SuppressDiagnostic) |
3669 | Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
3670 | AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers |
3671 | : diag::err_template_spec_extra_headers) |
3672 | << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), |
3673 | ParamLists[ParamLists.size() - 2]->getRAngleLoc()); |
3674 | |
3675 | // If there was a specialization somewhere, such that 'template<>' is |
3676 | // not required, and there were any 'template<>' headers, note where the |
3677 | // specialization occurred. |
3678 | if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader && |
3679 | !SuppressDiagnostic) |
3680 | Diag(ExplicitSpecLoc, |
3681 | diag::note_explicit_template_spec_does_not_need_header) |
3682 | << NestedTypes.back(); |
3683 | |
3684 | // We have a template parameter list with no corresponding scope, which |
3685 | // means that the resulting template declaration can't be instantiated |
3686 | // properly (we'll end up with dependent nodes when we shouldn't). |
3687 | if (!AllExplicitSpecHeaders) |
3688 | Invalid = true; |
3689 | } |
3690 | |
3691 | // C++ [temp.expl.spec]p16: |
3692 | // In an explicit specialization declaration for a member of a class |
3693 | // template or a member template that ap- pears in namespace scope, the |
3694 | // member template and some of its enclosing class templates may remain |
3695 | // unspecialized, except that the declaration shall not explicitly |
3696 | // specialize a class member template if its en- closing class templates |
3697 | // are not explicitly specialized as well. |
3698 | if (ParamLists.back()->size() == 0 && |
3699 | CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
3700 | false)) |
3701 | return nullptr; |
3702 | |
3703 | // Return the last template parameter list, which corresponds to the |
3704 | // entity being declared. |
3705 | return ParamLists.back(); |
3706 | } |
3707 | |
3708 | void Sema::NoteAllFoundTemplates(TemplateName Name) { |
3709 | if (TemplateDecl *Template = Name.getAsTemplateDecl()) { |
3710 | Diag(Template->getLocation(), diag::note_template_declared_here) |
3711 | << (isa<FunctionTemplateDecl>(Template) |
3712 | ? 0 |
3713 | : isa<ClassTemplateDecl>(Template) |
3714 | ? 1 |
3715 | : isa<VarTemplateDecl>(Template) |
3716 | ? 2 |
3717 | : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) |
3718 | << Template->getDeclName(); |
3719 | return; |
3720 | } |
3721 | |
3722 | if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { |
3723 | for (OverloadedTemplateStorage::iterator I = OST->begin(), |
3724 | IEnd = OST->end(); |
3725 | I != IEnd; ++I) |
3726 | Diag((*I)->getLocation(), diag::note_template_declared_here) |
3727 | << 0 << (*I)->getDeclName(); |
3728 | |
3729 | return; |
3730 | } |
3731 | } |
3732 | |
3733 | static QualType |
3734 | checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, |
3735 | ArrayRef<TemplateArgument> Converted, |
3736 | SourceLocation TemplateLoc, |
3737 | TemplateArgumentListInfo &TemplateArgs) { |
3738 | ASTContext &Context = SemaRef.getASTContext(); |
3739 | |
3740 | switch (BTD->getBuiltinTemplateKind()) { |
3741 | case BTK__make_integer_seq: { |
3742 | // Specializations of __make_integer_seq<S, T, N> are treated like |
3743 | // S<T, 0, ..., N-1>. |
3744 | |
3745 | QualType OrigType = Converted[1].getAsType(); |
3746 | // C++14 [inteseq.intseq]p1: |
3747 | // T shall be an integer type. |
3748 | if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) { |
3749 | SemaRef.Diag(TemplateArgs[1].getLocation(), |
3750 | diag::err_integer_sequence_integral_element_type); |
3751 | return QualType(); |
3752 | } |
3753 | |
3754 | TemplateArgument NumArgsArg = Converted[2]; |
3755 | if (NumArgsArg.isDependent()) |
3756 | return Context.getCanonicalTemplateSpecializationType(T: TemplateName(BTD), |
3757 | Args: Converted); |
3758 | |
3759 | TemplateArgumentListInfo SyntheticTemplateArgs; |
3760 | // The type argument, wrapped in substitution sugar, gets reused as the |
3761 | // first template argument in the synthetic template argument list. |
3762 | SyntheticTemplateArgs.addArgument( |
3763 | Loc: TemplateArgumentLoc(TemplateArgument(OrigType), |
3764 | SemaRef.Context.getTrivialTypeSourceInfo( |
3765 | T: OrigType, Loc: TemplateArgs[1].getLocation()))); |
3766 | |
3767 | if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) { |
3768 | // Expand N into 0 ... N-1. |
3769 | for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); |
3770 | I < NumArgs; ++I) { |
3771 | TemplateArgument TA(Context, I, OrigType); |
3772 | SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc( |
3773 | Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation())); |
3774 | } |
3775 | } else { |
3776 | // C++14 [inteseq.make]p1: |
3777 | // If N is negative the program is ill-formed. |
3778 | SemaRef.Diag(TemplateArgs[2].getLocation(), |
3779 | diag::err_integer_sequence_negative_length); |
3780 | return QualType(); |
3781 | } |
3782 | |
3783 | // The first template argument will be reused as the template decl that |
3784 | // our synthetic template arguments will be applied to. |
3785 | return SemaRef.CheckTemplateIdType(Template: Converted[0].getAsTemplate(), |
3786 | TemplateLoc, TemplateArgs&: SyntheticTemplateArgs); |
3787 | } |
3788 | |
3789 | case BTK__type_pack_element: |
3790 | // Specializations of |
3791 | // __type_pack_element<Index, T_1, ..., T_N> |
3792 | // are treated like T_Index. |
3793 | assert(Converted.size() == 2 && |
3794 | "__type_pack_element should be given an index and a parameter pack" ); |
3795 | |
3796 | TemplateArgument IndexArg = Converted[0], Ts = Converted[1]; |
3797 | if (IndexArg.isDependent() || Ts.isDependent()) |
3798 | return Context.getCanonicalTemplateSpecializationType(T: TemplateName(BTD), |
3799 | Args: Converted); |
3800 | |
3801 | llvm::APSInt Index = IndexArg.getAsIntegral(); |
3802 | assert(Index >= 0 && "the index used with __type_pack_element should be of " |
3803 | "type std::size_t, and hence be non-negative" ); |
3804 | // If the Index is out of bounds, the program is ill-formed. |
3805 | if (Index >= Ts.pack_size()) { |
3806 | SemaRef.Diag(TemplateArgs[0].getLocation(), |
3807 | diag::err_type_pack_element_out_of_bounds); |
3808 | return QualType(); |
3809 | } |
3810 | |
3811 | // We simply return the type at index `Index`. |
3812 | int64_t N = Index.getExtValue(); |
3813 | return Ts.getPackAsArray()[N].getAsType(); |
3814 | } |
3815 | llvm_unreachable("unexpected BuiltinTemplateDecl!" ); |
3816 | } |
3817 | |
3818 | /// Determine whether this alias template is "enable_if_t". |
3819 | /// libc++ >=14 uses "__enable_if_t" in C++11 mode. |
3820 | static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) { |
3821 | return AliasTemplate->getName().equals("enable_if_t" ) || |
3822 | AliasTemplate->getName().equals("__enable_if_t" ); |
3823 | } |
3824 | |
3825 | /// Collect all of the separable terms in the given condition, which |
3826 | /// might be a conjunction. |
3827 | /// |
3828 | /// FIXME: The right answer is to convert the logical expression into |
3829 | /// disjunctive normal form, so we can find the first failed term |
3830 | /// within each possible clause. |
3831 | static void collectConjunctionTerms(Expr *Clause, |
3832 | SmallVectorImpl<Expr *> &Terms) { |
3833 | if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) { |
3834 | if (BinOp->getOpcode() == BO_LAnd) { |
3835 | collectConjunctionTerms(Clause: BinOp->getLHS(), Terms); |
3836 | collectConjunctionTerms(Clause: BinOp->getRHS(), Terms); |
3837 | return; |
3838 | } |
3839 | } |
3840 | |
3841 | Terms.push_back(Elt: Clause); |
3842 | } |
3843 | |
3844 | // The ranges-v3 library uses an odd pattern of a top-level "||" with |
3845 | // a left-hand side that is value-dependent but never true. Identify |
3846 | // the idiom and ignore that term. |
3847 | static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) { |
3848 | // Top-level '||'. |
3849 | auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts()); |
3850 | if (!BinOp) return Cond; |
3851 | |
3852 | if (BinOp->getOpcode() != BO_LOr) return Cond; |
3853 | |
3854 | // With an inner '==' that has a literal on the right-hand side. |
3855 | Expr *LHS = BinOp->getLHS(); |
3856 | auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts()); |
3857 | if (!InnerBinOp) return Cond; |
3858 | |
3859 | if (InnerBinOp->getOpcode() != BO_EQ || |
3860 | !isa<IntegerLiteral>(Val: InnerBinOp->getRHS())) |
3861 | return Cond; |
3862 | |
3863 | // If the inner binary operation came from a macro expansion named |
3864 | // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side |
3865 | // of the '||', which is the real, user-provided condition. |
3866 | SourceLocation Loc = InnerBinOp->getExprLoc(); |
3867 | if (!Loc.isMacroID()) return Cond; |
3868 | |
3869 | StringRef MacroName = PP.getImmediateMacroName(Loc); |
3870 | if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_" ) |
3871 | return BinOp->getRHS(); |
3872 | |
3873 | return Cond; |
3874 | } |
3875 | |
3876 | namespace { |
3877 | |
3878 | // A PrinterHelper that prints more helpful diagnostics for some sub-expressions |
3879 | // within failing boolean expression, such as substituting template parameters |
3880 | // for actual types. |
3881 | class FailedBooleanConditionPrinterHelper : public PrinterHelper { |
3882 | public: |
3883 | explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P) |
3884 | : Policy(P) {} |
3885 | |
3886 | bool handledStmt(Stmt *E, raw_ostream &OS) override { |
3887 | const auto *DR = dyn_cast<DeclRefExpr>(Val: E); |
3888 | if (DR && DR->getQualifier()) { |
3889 | // If this is a qualified name, expand the template arguments in nested |
3890 | // qualifiers. |
3891 | DR->getQualifier()->print(OS, Policy, ResolveTemplateArguments: true); |
3892 | // Then print the decl itself. |
3893 | const ValueDecl *VD = DR->getDecl(); |
3894 | OS << VD->getName(); |
3895 | if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) { |
3896 | // This is a template variable, print the expanded template arguments. |
3897 | printTemplateArgumentList( |
3898 | OS, IV->getTemplateArgs().asArray(), Policy, |
3899 | IV->getSpecializedTemplate()->getTemplateParameters()); |
3900 | } |
3901 | return true; |
3902 | } |
3903 | return false; |
3904 | } |
3905 | |
3906 | private: |
3907 | const PrintingPolicy Policy; |
3908 | }; |
3909 | |
3910 | } // end anonymous namespace |
3911 | |
3912 | std::pair<Expr *, std::string> |
3913 | Sema::findFailedBooleanCondition(Expr *Cond) { |
3914 | Cond = lookThroughRangesV3Condition(PP, Cond); |
3915 | |
3916 | // Separate out all of the terms in a conjunction. |
3917 | SmallVector<Expr *, 4> Terms; |
3918 | collectConjunctionTerms(Clause: Cond, Terms); |
3919 | |
3920 | // Determine which term failed. |
3921 | Expr *FailedCond = nullptr; |
3922 | for (Expr *Term : Terms) { |
3923 | Expr *TermAsWritten = Term->IgnoreParenImpCasts(); |
3924 | |
3925 | // Literals are uninteresting. |
3926 | if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) || |
3927 | isa<IntegerLiteral>(Val: TermAsWritten)) |
3928 | continue; |
3929 | |
3930 | // The initialization of the parameter from the argument is |
3931 | // a constant-evaluated context. |
3932 | EnterExpressionEvaluationContext ConstantEvaluated( |
3933 | *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
3934 | |
3935 | bool Succeeded; |
3936 | if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) && |
3937 | !Succeeded) { |
3938 | FailedCond = TermAsWritten; |
3939 | break; |
3940 | } |
3941 | } |
3942 | if (!FailedCond) |
3943 | FailedCond = Cond->IgnoreParenImpCasts(); |
3944 | |
3945 | std::string Description; |
3946 | { |
3947 | llvm::raw_string_ostream Out(Description); |
3948 | PrintingPolicy Policy = getPrintingPolicy(); |
3949 | Policy.PrintCanonicalTypes = true; |
3950 | FailedBooleanConditionPrinterHelper Helper(Policy); |
3951 | FailedCond->printPretty(Out, &Helper, Policy, 0, "\n" , nullptr); |
3952 | } |
3953 | return { FailedCond, Description }; |
3954 | } |
3955 | |
3956 | QualType Sema::CheckTemplateIdType(TemplateName Name, |
3957 | SourceLocation TemplateLoc, |
3958 | TemplateArgumentListInfo &TemplateArgs) { |
3959 | DependentTemplateName *DTN |
3960 | = Name.getUnderlying().getAsDependentTemplateName(); |
3961 | if (DTN && DTN->isIdentifier()) |
3962 | // When building a template-id where the template-name is dependent, |
3963 | // assume the template is a type template. Either our assumption is |
3964 | // correct, or the code is ill-formed and will be diagnosed when the |
3965 | // dependent name is substituted. |
3966 | return Context.getDependentTemplateSpecializationType( |
3967 | Keyword: ElaboratedTypeKeyword::None, NNS: DTN->getQualifier(), Name: DTN->getIdentifier(), |
3968 | Args: TemplateArgs.arguments()); |
3969 | |
3970 | if (Name.getAsAssumedTemplateName() && |
3971 | resolveAssumedTemplateNameAsType(/*Scope*/S: nullptr, Name, NameLoc: TemplateLoc)) |
3972 | return QualType(); |
3973 | |
3974 | TemplateDecl *Template = Name.getAsTemplateDecl(); |
3975 | if (!Template || isa<FunctionTemplateDecl>(Val: Template) || |
3976 | isa<VarTemplateDecl>(Val: Template) || isa<ConceptDecl>(Val: Template)) { |
3977 | // We might have a substituted template template parameter pack. If so, |
3978 | // build a template specialization type for it. |
3979 | if (Name.getAsSubstTemplateTemplateParmPack()) |
3980 | return Context.getTemplateSpecializationType(T: Name, |
3981 | Args: TemplateArgs.arguments()); |
3982 | |
3983 | Diag(TemplateLoc, diag::err_template_id_not_a_type) |
3984 | << Name; |
3985 | NoteAllFoundTemplates(Name); |
3986 | return QualType(); |
3987 | } |
3988 | |
3989 | // Check that the template argument list is well-formed for this |
3990 | // template. |
3991 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
3992 | if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, PartialTemplateArgs: false, |
3993 | SugaredConverted, CanonicalConverted, |
3994 | /*UpdateArgsWithConversions=*/true)) |
3995 | return QualType(); |
3996 | |
3997 | QualType CanonType; |
3998 | |
3999 | if (TypeAliasTemplateDecl *AliasTemplate = |
4000 | dyn_cast<TypeAliasTemplateDecl>(Val: Template)) { |
4001 | |
4002 | // Find the canonical type for this type alias template specialization. |
4003 | TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); |
4004 | if (Pattern->isInvalidDecl()) |
4005 | return QualType(); |
4006 | |
4007 | // Only substitute for the innermost template argument list. |
4008 | MultiLevelTemplateArgumentList TemplateArgLists; |
4009 | TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted, |
4010 | /*Final=*/false); |
4011 | TemplateArgLists.addOuterRetainedLevels( |
4012 | Num: AliasTemplate->getTemplateParameters()->getDepth()); |
4013 | |
4014 | LocalInstantiationScope Scope(*this); |
4015 | InstantiatingTemplate Inst(*this, TemplateLoc, Template); |
4016 | if (Inst.isInvalid()) |
4017 | return QualType(); |
4018 | |
4019 | CanonType = SubstType(Pattern->getUnderlyingType(), |
4020 | TemplateArgLists, AliasTemplate->getLocation(), |
4021 | AliasTemplate->getDeclName()); |
4022 | if (CanonType.isNull()) { |
4023 | // If this was enable_if and we failed to find the nested type |
4024 | // within enable_if in a SFINAE context, dig out the specific |
4025 | // enable_if condition that failed and present that instead. |
4026 | if (isEnableIfAliasTemplate(AliasTemplate)) { |
4027 | if (auto DeductionInfo = isSFINAEContext()) { |
4028 | if (*DeductionInfo && |
4029 | (*DeductionInfo)->hasSFINAEDiagnostic() && |
4030 | (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() == |
4031 | diag::err_typename_nested_not_found_enable_if && |
4032 | TemplateArgs[0].getArgument().getKind() |
4033 | == TemplateArgument::Expression) { |
4034 | Expr *FailedCond; |
4035 | std::string FailedDescription; |
4036 | std::tie(args&: FailedCond, args&: FailedDescription) = |
4037 | findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression()); |
4038 | |
4039 | // Remove the old SFINAE diagnostic. |
4040 | PartialDiagnosticAt OldDiag = |
4041 | {SourceLocation(), PartialDiagnostic::NullDiagnostic()}; |
4042 | (*DeductionInfo)->takeSFINAEDiagnostic(PD&: OldDiag); |
4043 | |
4044 | // Add a new SFINAE diagnostic specifying which condition |
4045 | // failed. |
4046 | (*DeductionInfo)->addSFINAEDiagnostic( |
4047 | OldDiag.first, |
4048 | PDiag(diag::err_typename_nested_not_found_requirement) |
4049 | << FailedDescription |
4050 | << FailedCond->getSourceRange()); |
4051 | } |
4052 | } |
4053 | } |
4054 | |
4055 | return QualType(); |
4056 | } |
4057 | } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) { |
4058 | CanonType = checkBuiltinTemplateIdType(SemaRef&: *this, BTD, Converted: SugaredConverted, |
4059 | TemplateLoc, TemplateArgs); |
4060 | } else if (Name.isDependent() || |
4061 | TemplateSpecializationType::anyDependentTemplateArguments( |
4062 | TemplateArgs, Converted: CanonicalConverted)) { |
4063 | // This class template specialization is a dependent |
4064 | // type. Therefore, its canonical type is another class template |
4065 | // specialization type that contains all of the converted |
4066 | // arguments in canonical form. This ensures that, e.g., A<T> and |
4067 | // A<T, T> have identical types when A is declared as: |
4068 | // |
4069 | // template<typename T, typename U = T> struct A; |
4070 | CanonType = Context.getCanonicalTemplateSpecializationType( |
4071 | T: Name, Args: CanonicalConverted); |
4072 | |
4073 | // This might work out to be a current instantiation, in which |
4074 | // case the canonical type needs to be the InjectedClassNameType. |
4075 | // |
4076 | // TODO: in theory this could be a simple hashtable lookup; most |
4077 | // changes to CurContext don't change the set of current |
4078 | // instantiations. |
4079 | if (isa<ClassTemplateDecl>(Val: Template)) { |
4080 | for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { |
4081 | // If we get out to a namespace, we're done. |
4082 | if (Ctx->isFileContext()) break; |
4083 | |
4084 | // If this isn't a record, keep looking. |
4085 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx); |
4086 | if (!Record) continue; |
4087 | |
4088 | // Look for one of the two cases with InjectedClassNameTypes |
4089 | // and check whether it's the same template. |
4090 | if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) && |
4091 | !Record->getDescribedClassTemplate()) |
4092 | continue; |
4093 | |
4094 | // Fetch the injected class name type and check whether its |
4095 | // injected type is equal to the type we just built. |
4096 | QualType ICNT = Context.getTypeDeclType(Record); |
4097 | QualType Injected = cast<InjectedClassNameType>(Val&: ICNT) |
4098 | ->getInjectedSpecializationType(); |
4099 | |
4100 | if (CanonType != Injected->getCanonicalTypeInternal()) |
4101 | continue; |
4102 | |
4103 | // If so, the canonical type of this TST is the injected |
4104 | // class name type of the record we just found. |
4105 | assert(ICNT.isCanonical()); |
4106 | CanonType = ICNT; |
4107 | break; |
4108 | } |
4109 | } |
4110 | } else if (ClassTemplateDecl *ClassTemplate = |
4111 | dyn_cast<ClassTemplateDecl>(Val: Template)) { |
4112 | // Find the class template specialization declaration that |
4113 | // corresponds to these arguments. |
4114 | void *InsertPos = nullptr; |
4115 | ClassTemplateSpecializationDecl *Decl = |
4116 | ClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
4117 | if (!Decl) { |
4118 | // This is the first time we have referenced this class template |
4119 | // specialization. Create the canonical declaration and add it to |
4120 | // the set of specializations. |
4121 | Decl = ClassTemplateSpecializationDecl::Create( |
4122 | Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(), |
4123 | DC: ClassTemplate->getDeclContext(), |
4124 | StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(), |
4125 | IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, |
4126 | PrevDecl: nullptr); |
4127 | ClassTemplate->AddSpecialization(D: Decl, InsertPos); |
4128 | if (ClassTemplate->isOutOfLine()) |
4129 | Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); |
4130 | } |
4131 | |
4132 | if (Decl->getSpecializationKind() == TSK_Undeclared && |
4133 | ClassTemplate->getTemplatedDecl()->hasAttrs()) { |
4134 | InstantiatingTemplate Inst(*this, TemplateLoc, Decl); |
4135 | if (!Inst.isInvalid()) { |
4136 | MultiLevelTemplateArgumentList TemplateArgLists(Template, |
4137 | CanonicalConverted, |
4138 | /*Final=*/false); |
4139 | InstantiateAttrsForDecl(TemplateArgLists, |
4140 | ClassTemplate->getTemplatedDecl(), Decl); |
4141 | } |
4142 | } |
4143 | |
4144 | // Diagnose uses of this specialization. |
4145 | (void)DiagnoseUseOfDecl(Decl, TemplateLoc); |
4146 | |
4147 | CanonType = Context.getTypeDeclType(Decl); |
4148 | assert(isa<RecordType>(CanonType) && |
4149 | "type of non-dependent specialization is not a RecordType" ); |
4150 | } else { |
4151 | llvm_unreachable("Unhandled template kind" ); |
4152 | } |
4153 | |
4154 | // Build the fully-sugared type for this class template |
4155 | // specialization, which refers back to the class template |
4156 | // specialization we created or found. |
4157 | return Context.getTemplateSpecializationType(T: Name, Args: TemplateArgs.arguments(), |
4158 | Canon: CanonType); |
4159 | } |
4160 | |
4161 | void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName, |
4162 | TemplateNameKind &TNK, |
4163 | SourceLocation NameLoc, |
4164 | IdentifierInfo *&II) { |
4165 | assert(TNK == TNK_Undeclared_template && "not an undeclared template name" ); |
4166 | |
4167 | TemplateName Name = ParsedName.get(); |
4168 | auto *ATN = Name.getAsAssumedTemplateName(); |
4169 | assert(ATN && "not an assumed template name" ); |
4170 | II = ATN->getDeclName().getAsIdentifierInfo(); |
4171 | |
4172 | if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) { |
4173 | // Resolved to a type template name. |
4174 | ParsedName = TemplateTy::make(P: Name); |
4175 | TNK = TNK_Type_template; |
4176 | } |
4177 | } |
4178 | |
4179 | bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, |
4180 | SourceLocation NameLoc, |
4181 | bool Diagnose) { |
4182 | // We assumed this undeclared identifier to be an (ADL-only) function |
4183 | // template name, but it was used in a context where a type was required. |
4184 | // Try to typo-correct it now. |
4185 | AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName(); |
4186 | assert(ATN && "not an assumed template name" ); |
4187 | |
4188 | LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName); |
4189 | struct CandidateCallback : CorrectionCandidateCallback { |
4190 | bool ValidateCandidate(const TypoCorrection &TC) override { |
4191 | return TC.getCorrectionDecl() && |
4192 | getAsTypeTemplateDecl(TC.getCorrectionDecl()); |
4193 | } |
4194 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
4195 | return std::make_unique<CandidateCallback>(args&: *this); |
4196 | } |
4197 | } FilterCCC; |
4198 | |
4199 | TypoCorrection Corrected = |
4200 | CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: nullptr, |
4201 | CCC&: FilterCCC, Mode: CTK_ErrorRecovery); |
4202 | if (Corrected && Corrected.getFoundDecl()) { |
4203 | diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) |
4204 | << ATN->getDeclName()); |
4205 | Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()); |
4206 | return false; |
4207 | } |
4208 | |
4209 | if (Diagnose) |
4210 | Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName(); |
4211 | return true; |
4212 | } |
4213 | |
4214 | TypeResult Sema::ActOnTemplateIdType( |
4215 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
4216 | TemplateTy TemplateD, IdentifierInfo *TemplateII, |
4217 | SourceLocation TemplateIILoc, SourceLocation LAngleLoc, |
4218 | ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc, |
4219 | bool IsCtorOrDtorName, bool IsClassName, |
4220 | ImplicitTypenameContext AllowImplicitTypename) { |
4221 | if (SS.isInvalid()) |
4222 | return true; |
4223 | |
4224 | if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { |
4225 | DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false); |
4226 | |
4227 | // C++ [temp.res]p3: |
4228 | // A qualified-id that refers to a type and in which the |
4229 | // nested-name-specifier depends on a template-parameter (14.6.2) |
4230 | // shall be prefixed by the keyword typename to indicate that the |
4231 | // qualified-id denotes a type, forming an |
4232 | // elaborated-type-specifier (7.1.5.3). |
4233 | if (!LookupCtx && isDependentScopeSpecifier(SS)) { |
4234 | // C++2a relaxes some of those restrictions in [temp.res]p5. |
4235 | if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { |
4236 | if (getLangOpts().CPlusPlus20) |
4237 | Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename); |
4238 | else |
4239 | Diag(SS.getBeginLoc(), diag::ext_implicit_typename) |
4240 | << SS.getScopeRep() << TemplateII->getName() |
4241 | << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename " ); |
4242 | } else |
4243 | Diag(SS.getBeginLoc(), diag::err_typename_missing_template) |
4244 | << SS.getScopeRep() << TemplateII->getName(); |
4245 | |
4246 | // FIXME: This is not quite correct recovery as we don't transform SS |
4247 | // into the corresponding dependent form (and we don't diagnose missing |
4248 | // 'template' keywords within SS as a result). |
4249 | return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc, |
4250 | TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc, |
4251 | TemplateArgs: TemplateArgsIn, RAngleLoc); |
4252 | } |
4253 | |
4254 | // Per C++ [class.qual]p2, if the template-id was an injected-class-name, |
4255 | // it's not actually allowed to be used as a type in most cases. Because |
4256 | // we annotate it before we know whether it's valid, we have to check for |
4257 | // this case here. |
4258 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx); |
4259 | if (LookupRD && LookupRD->getIdentifier() == TemplateII) { |
4260 | Diag(TemplateIILoc, |
4261 | TemplateKWLoc.isInvalid() |
4262 | ? diag::err_out_of_line_qualified_id_type_names_constructor |
4263 | : diag::ext_out_of_line_qualified_id_type_names_constructor) |
4264 | << TemplateII << 0 /*injected-class-name used as template name*/ |
4265 | << 1 /*if any keyword was present, it was 'template'*/; |
4266 | } |
4267 | } |
4268 | |
4269 | TemplateName Template = TemplateD.get(); |
4270 | if (Template.getAsAssumedTemplateName() && |
4271 | resolveAssumedTemplateNameAsType(S, Name&: Template, NameLoc: TemplateIILoc)) |
4272 | return true; |
4273 | |
4274 | // Translate the parser's template argument list in our AST format. |
4275 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
4276 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
4277 | |
4278 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
4279 | assert(SS.getScopeRep() == DTN->getQualifier()); |
4280 | QualType T = Context.getDependentTemplateSpecializationType( |
4281 | Keyword: ElaboratedTypeKeyword::None, NNS: DTN->getQualifier(), Name: DTN->getIdentifier(), |
4282 | Args: TemplateArgs.arguments()); |
4283 | // Build type-source information. |
4284 | TypeLocBuilder TLB; |
4285 | DependentTemplateSpecializationTypeLoc SpecTL |
4286 | = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
4287 | SpecTL.setElaboratedKeywordLoc(SourceLocation()); |
4288 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4289 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4290 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
4291 | SpecTL.setLAngleLoc(LAngleLoc); |
4292 | SpecTL.setRAngleLoc(RAngleLoc); |
4293 | for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
4294 | SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo()); |
4295 | return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T)); |
4296 | } |
4297 | |
4298 | QualType SpecTy = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs); |
4299 | if (SpecTy.isNull()) |
4300 | return true; |
4301 | |
4302 | // Build type-source information. |
4303 | TypeLocBuilder TLB; |
4304 | TemplateSpecializationTypeLoc SpecTL = |
4305 | TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy); |
4306 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4307 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
4308 | SpecTL.setLAngleLoc(LAngleLoc); |
4309 | SpecTL.setRAngleLoc(RAngleLoc); |
4310 | for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
4311 | SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo()); |
4312 | |
4313 | // Create an elaborated-type-specifier containing the nested-name-specifier. |
4314 | QualType ElTy = |
4315 | getElaboratedType(Keyword: ElaboratedTypeKeyword::None, |
4316 | SS: !IsCtorOrDtorName ? SS : CXXScopeSpec(), T: SpecTy); |
4317 | ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: ElTy); |
4318 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
4319 | if (!ElabTL.isEmpty()) |
4320 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4321 | return CreateParsedType(T: ElTy, TInfo: TLB.getTypeSourceInfo(Context, T: ElTy)); |
4322 | } |
4323 | |
4324 | TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, |
4325 | TypeSpecifierType TagSpec, |
4326 | SourceLocation TagLoc, |
4327 | CXXScopeSpec &SS, |
4328 | SourceLocation TemplateKWLoc, |
4329 | TemplateTy TemplateD, |
4330 | SourceLocation TemplateLoc, |
4331 | SourceLocation LAngleLoc, |
4332 | ASTTemplateArgsPtr TemplateArgsIn, |
4333 | SourceLocation RAngleLoc) { |
4334 | if (SS.isInvalid()) |
4335 | return TypeResult(true); |
4336 | |
4337 | TemplateName Template = TemplateD.get(); |
4338 | |
4339 | // Translate the parser's template argument list in our AST format. |
4340 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
4341 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
4342 | |
4343 | // Determine the tag kind |
4344 | TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec); |
4345 | ElaboratedTypeKeyword Keyword |
4346 | = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind); |
4347 | |
4348 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
4349 | assert(SS.getScopeRep() == DTN->getQualifier()); |
4350 | QualType T = Context.getDependentTemplateSpecializationType( |
4351 | Keyword, NNS: DTN->getQualifier(), Name: DTN->getIdentifier(), |
4352 | Args: TemplateArgs.arguments()); |
4353 | |
4354 | // Build type-source information. |
4355 | TypeLocBuilder TLB; |
4356 | DependentTemplateSpecializationTypeLoc SpecTL |
4357 | = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
4358 | SpecTL.setElaboratedKeywordLoc(TagLoc); |
4359 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4360 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4361 | SpecTL.setTemplateNameLoc(TemplateLoc); |
4362 | SpecTL.setLAngleLoc(LAngleLoc); |
4363 | SpecTL.setRAngleLoc(RAngleLoc); |
4364 | for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
4365 | SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo()); |
4366 | return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T)); |
4367 | } |
4368 | |
4369 | if (TypeAliasTemplateDecl *TAT = |
4370 | dyn_cast_or_null<TypeAliasTemplateDecl>(Val: Template.getAsTemplateDecl())) { |
4371 | // C++0x [dcl.type.elab]p2: |
4372 | // If the identifier resolves to a typedef-name or the simple-template-id |
4373 | // resolves to an alias template specialization, the |
4374 | // elaborated-type-specifier is ill-formed. |
4375 | Diag(TemplateLoc, diag::err_tag_reference_non_tag) |
4376 | << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind); |
4377 | Diag(TAT->getLocation(), diag::note_declared_at); |
4378 | } |
4379 | |
4380 | QualType Result = CheckTemplateIdType(Name: Template, TemplateLoc, TemplateArgs); |
4381 | if (Result.isNull()) |
4382 | return TypeResult(true); |
4383 | |
4384 | // Check the tag kind |
4385 | if (const RecordType *RT = Result->getAs<RecordType>()) { |
4386 | RecordDecl *D = RT->getDecl(); |
4387 | |
4388 | IdentifierInfo *Id = D->getIdentifier(); |
4389 | assert(Id && "templated class must have an identifier" ); |
4390 | |
4391 | if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, |
4392 | TagLoc, Id)) { |
4393 | Diag(TagLoc, diag::err_use_with_wrong_tag) |
4394 | << Result |
4395 | << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); |
4396 | Diag(D->getLocation(), diag::note_previous_use); |
4397 | } |
4398 | } |
4399 | |
4400 | // Provide source-location information for the template specialization. |
4401 | TypeLocBuilder TLB; |
4402 | TemplateSpecializationTypeLoc SpecTL |
4403 | = TLB.push<TemplateSpecializationTypeLoc>(T: Result); |
4404 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4405 | SpecTL.setTemplateNameLoc(TemplateLoc); |
4406 | SpecTL.setLAngleLoc(LAngleLoc); |
4407 | SpecTL.setRAngleLoc(RAngleLoc); |
4408 | for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
4409 | SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo()); |
4410 | |
4411 | // Construct an elaborated type containing the nested-name-specifier (if any) |
4412 | // and tag keyword. |
4413 | Result = Context.getElaboratedType(Keyword, NNS: SS.getScopeRep(), NamedType: Result); |
4414 | ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: Result); |
4415 | ElabTL.setElaboratedKeywordLoc(TagLoc); |
4416 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4417 | return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result)); |
4418 | } |
4419 | |
4420 | static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, |
4421 | NamedDecl *PrevDecl, |
4422 | SourceLocation Loc, |
4423 | bool IsPartialSpecialization); |
4424 | |
4425 | static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); |
4426 | |
4427 | static bool isTemplateArgumentTemplateParameter( |
4428 | const TemplateArgument &Arg, unsigned Depth, unsigned Index) { |
4429 | switch (Arg.getKind()) { |
4430 | case TemplateArgument::Null: |
4431 | case TemplateArgument::NullPtr: |
4432 | case TemplateArgument::Integral: |
4433 | case TemplateArgument::Declaration: |
4434 | case TemplateArgument::StructuralValue: |
4435 | case TemplateArgument::Pack: |
4436 | case TemplateArgument::TemplateExpansion: |
4437 | return false; |
4438 | |
4439 | case TemplateArgument::Type: { |
4440 | QualType Type = Arg.getAsType(); |
4441 | const TemplateTypeParmType *TPT = |
4442 | Arg.getAsType()->getAs<TemplateTypeParmType>(); |
4443 | return TPT && !Type.hasQualifiers() && |
4444 | TPT->getDepth() == Depth && TPT->getIndex() == Index; |
4445 | } |
4446 | |
4447 | case TemplateArgument::Expression: { |
4448 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr()); |
4449 | if (!DRE || !DRE->getDecl()) |
4450 | return false; |
4451 | const NonTypeTemplateParmDecl *NTTP = |
4452 | dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl()); |
4453 | return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; |
4454 | } |
4455 | |
4456 | case TemplateArgument::Template: |
4457 | const TemplateTemplateParmDecl *TTP = |
4458 | dyn_cast_or_null<TemplateTemplateParmDecl>( |
4459 | Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); |
4460 | return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; |
4461 | } |
4462 | llvm_unreachable("unexpected kind of template argument" ); |
4463 | } |
4464 | |
4465 | static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, |
4466 | ArrayRef<TemplateArgument> Args) { |
4467 | if (Params->size() != Args.size()) |
4468 | return false; |
4469 | |
4470 | unsigned Depth = Params->getDepth(); |
4471 | |
4472 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { |
4473 | TemplateArgument Arg = Args[I]; |
4474 | |
4475 | // If the parameter is a pack expansion, the argument must be a pack |
4476 | // whose only element is a pack expansion. |
4477 | if (Params->getParam(Idx: I)->isParameterPack()) { |
4478 | if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || |
4479 | !Arg.pack_begin()->isPackExpansion()) |
4480 | return false; |
4481 | Arg = Arg.pack_begin()->getPackExpansionPattern(); |
4482 | } |
4483 | |
4484 | if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I)) |
4485 | return false; |
4486 | } |
4487 | |
4488 | return true; |
4489 | } |
4490 | |
4491 | template<typename PartialSpecDecl> |
4492 | static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) { |
4493 | if (Partial->getDeclContext()->isDependentContext()) |
4494 | return; |
4495 | |
4496 | // FIXME: Get the TDK from deduction in order to provide better diagnostics |
4497 | // for non-substitution-failure issues? |
4498 | TemplateDeductionInfo Info(Partial->getLocation()); |
4499 | if (S.isMoreSpecializedThanPrimary(Partial, Info)) |
4500 | return; |
4501 | |
4502 | auto *Template = Partial->getSpecializedTemplate(); |
4503 | S.Diag(Partial->getLocation(), |
4504 | diag::ext_partial_spec_not_more_specialized_than_primary) |
4505 | << isa<VarTemplateDecl>(Template); |
4506 | |
4507 | if (Info.hasSFINAEDiagnostic()) { |
4508 | PartialDiagnosticAt Diag = {SourceLocation(), |
4509 | PartialDiagnostic::NullDiagnostic()}; |
4510 | Info.takeSFINAEDiagnostic(PD&: Diag); |
4511 | SmallString<128> SFINAEArgString; |
4512 | Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString); |
4513 | S.Diag(Diag.first, |
4514 | diag::note_partial_spec_not_more_specialized_than_primary) |
4515 | << SFINAEArgString; |
4516 | } |
4517 | |
4518 | S.NoteTemplateLocation(Decl: *Template); |
4519 | SmallVector<const Expr *, 3> PartialAC, TemplateAC; |
4520 | Template->getAssociatedConstraints(TemplateAC); |
4521 | Partial->getAssociatedConstraints(PartialAC); |
4522 | S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template, |
4523 | AC2: TemplateAC); |
4524 | } |
4525 | |
4526 | static void |
4527 | noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, |
4528 | const llvm::SmallBitVector &DeducibleParams) { |
4529 | for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { |
4530 | if (!DeducibleParams[I]) { |
4531 | NamedDecl *Param = TemplateParams->getParam(Idx: I); |
4532 | if (Param->getDeclName()) |
4533 | S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) |
4534 | << Param->getDeclName(); |
4535 | else |
4536 | S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) |
4537 | << "(anonymous)" ; |
4538 | } |
4539 | } |
4540 | } |
4541 | |
4542 | |
4543 | template<typename PartialSpecDecl> |
4544 | static void checkTemplatePartialSpecialization(Sema &S, |
4545 | PartialSpecDecl *Partial) { |
4546 | // C++1z [temp.class.spec]p8: (DR1495) |
4547 | // - The specialization shall be more specialized than the primary |
4548 | // template (14.5.5.2). |
4549 | checkMoreSpecializedThanPrimary(S, Partial); |
4550 | |
4551 | // C++ [temp.class.spec]p8: (DR1315) |
4552 | // - Each template-parameter shall appear at least once in the |
4553 | // template-id outside a non-deduced context. |
4554 | // C++1z [temp.class.spec.match]p3 (P0127R2) |
4555 | // If the template arguments of a partial specialization cannot be |
4556 | // deduced because of the structure of its template-parameter-list |
4557 | // and the template-id, the program is ill-formed. |
4558 | auto *TemplateParams = Partial->getTemplateParameters(); |
4559 | llvm::SmallBitVector DeducibleParams(TemplateParams->size()); |
4560 | S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, |
4561 | TemplateParams->getDepth(), DeducibleParams); |
4562 | |
4563 | if (!DeducibleParams.all()) { |
4564 | unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); |
4565 | S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible) |
4566 | << isa<VarTemplatePartialSpecializationDecl>(Partial) |
4567 | << (NumNonDeducible > 1) |
4568 | << SourceRange(Partial->getLocation(), |
4569 | Partial->getTemplateArgsAsWritten()->RAngleLoc); |
4570 | noteNonDeducibleParameters(S, TemplateParams, DeducibleParams); |
4571 | } |
4572 | } |
4573 | |
4574 | void Sema::CheckTemplatePartialSpecialization( |
4575 | ClassTemplatePartialSpecializationDecl *Partial) { |
4576 | checkTemplatePartialSpecialization(S&: *this, Partial); |
4577 | } |
4578 | |
4579 | void Sema::CheckTemplatePartialSpecialization( |
4580 | VarTemplatePartialSpecializationDecl *Partial) { |
4581 | checkTemplatePartialSpecialization(S&: *this, Partial); |
4582 | } |
4583 | |
4584 | void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) { |
4585 | // C++1z [temp.param]p11: |
4586 | // A template parameter of a deduction guide template that does not have a |
4587 | // default-argument shall be deducible from the parameter-type-list of the |
4588 | // deduction guide template. |
4589 | auto *TemplateParams = TD->getTemplateParameters(); |
4590 | llvm::SmallBitVector DeducibleParams(TemplateParams->size()); |
4591 | MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams); |
4592 | for (unsigned I = 0; I != TemplateParams->size(); ++I) { |
4593 | // A parameter pack is deducible (to an empty pack). |
4594 | auto *Param = TemplateParams->getParam(I); |
4595 | if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param)) |
4596 | DeducibleParams[I] = true; |
4597 | } |
4598 | |
4599 | if (!DeducibleParams.all()) { |
4600 | unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); |
4601 | Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible) |
4602 | << (NumNonDeducible > 1); |
4603 | noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams); |
4604 | } |
4605 | } |
4606 | |
4607 | DeclResult Sema::ActOnVarTemplateSpecialization( |
4608 | Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, |
4609 | SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, |
4610 | StorageClass SC, bool IsPartialSpecialization) { |
4611 | // D must be variable template id. |
4612 | assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && |
4613 | "Variable template specialization is declared with a template id." ); |
4614 | |
4615 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; |
4616 | TemplateArgumentListInfo TemplateArgs = |
4617 | makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId); |
4618 | SourceLocation TemplateNameLoc = D.getIdentifierLoc(); |
4619 | SourceLocation LAngleLoc = TemplateId->LAngleLoc; |
4620 | SourceLocation RAngleLoc = TemplateId->RAngleLoc; |
4621 | |
4622 | TemplateName Name = TemplateId->Template.get(); |
4623 | |
4624 | // The template-id must name a variable template. |
4625 | VarTemplateDecl *VarTemplate = |
4626 | dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl()); |
4627 | if (!VarTemplate) { |
4628 | NamedDecl *FnTemplate; |
4629 | if (auto *OTS = Name.getAsOverloadedTemplate()) |
4630 | FnTemplate = *OTS->begin(); |
4631 | else |
4632 | FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl()); |
4633 | if (FnTemplate) |
4634 | return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method) |
4635 | << FnTemplate->getDeclName(); |
4636 | return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) |
4637 | << IsPartialSpecialization; |
4638 | } |
4639 | |
4640 | // Check for unexpanded parameter packs in any of the template arguments. |
4641 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
4642 | if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I], |
4643 | UPPC: IsPartialSpecialization |
4644 | ? UPPC_PartialSpecialization |
4645 | : UPPC_ExplicitSpecialization)) |
4646 | return true; |
4647 | |
4648 | // Check that the template argument list is well-formed for this |
4649 | // template. |
4650 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4651 | if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, |
4652 | false, SugaredConverted, CanonicalConverted, |
4653 | /*UpdateArgsWithConversions=*/true)) |
4654 | return true; |
4655 | |
4656 | // Find the variable template (partial) specialization declaration that |
4657 | // corresponds to these arguments. |
4658 | if (IsPartialSpecialization) { |
4659 | if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate, |
4660 | TemplateArgs.size(), |
4661 | CanonicalConverted)) |
4662 | return true; |
4663 | |
4664 | // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we |
4665 | // also do them during instantiation. |
4666 | if (!Name.isDependent() && |
4667 | !TemplateSpecializationType::anyDependentTemplateArguments( |
4668 | TemplateArgs, Converted: CanonicalConverted)) { |
4669 | Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) |
4670 | << VarTemplate->getDeclName(); |
4671 | IsPartialSpecialization = false; |
4672 | } |
4673 | |
4674 | if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), |
4675 | CanonicalConverted) && |
4676 | (!Context.getLangOpts().CPlusPlus20 || |
4677 | !TemplateParams->hasAssociatedConstraints())) { |
4678 | // C++ [temp.class.spec]p9b3: |
4679 | // |
4680 | // -- The argument list of the specialization shall not be identical |
4681 | // to the implicit argument list of the primary template. |
4682 | Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) |
4683 | << /*variable template*/ 1 |
4684 | << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) |
4685 | << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); |
4686 | // FIXME: Recover from this by treating the declaration as a redeclaration |
4687 | // of the primary template. |
4688 | return true; |
4689 | } |
4690 | } |
4691 | |
4692 | void *InsertPos = nullptr; |
4693 | VarTemplateSpecializationDecl *PrevDecl = nullptr; |
4694 | |
4695 | if (IsPartialSpecialization) |
4696 | PrevDecl = VarTemplate->findPartialSpecialization( |
4697 | Args: CanonicalConverted, TPL: TemplateParams, InsertPos); |
4698 | else |
4699 | PrevDecl = VarTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
4700 | |
4701 | VarTemplateSpecializationDecl *Specialization = nullptr; |
4702 | |
4703 | // Check whether we can declare a variable template specialization in |
4704 | // the current scope. |
4705 | if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, |
4706 | TemplateNameLoc, |
4707 | IsPartialSpecialization)) |
4708 | return true; |
4709 | |
4710 | if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { |
4711 | // Since the only prior variable template specialization with these |
4712 | // arguments was referenced but not declared, reuse that |
4713 | // declaration node as our own, updating its source location and |
4714 | // the list of outer template parameters to reflect our new declaration. |
4715 | Specialization = PrevDecl; |
4716 | Specialization->setLocation(TemplateNameLoc); |
4717 | PrevDecl = nullptr; |
4718 | } else if (IsPartialSpecialization) { |
4719 | // Create a new class template partial specialization declaration node. |
4720 | VarTemplatePartialSpecializationDecl *PrevPartial = |
4721 | cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl); |
4722 | VarTemplatePartialSpecializationDecl *Partial = |
4723 | VarTemplatePartialSpecializationDecl::Create( |
4724 | Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, |
4725 | IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC, |
4726 | Args: CanonicalConverted, ArgInfos: TemplateArgs); |
4727 | |
4728 | if (!PrevPartial) |
4729 | VarTemplate->AddPartialSpecialization(D: Partial, InsertPos); |
4730 | Specialization = Partial; |
4731 | |
4732 | // If we are providing an explicit specialization of a member variable |
4733 | // template specialization, make a note of that. |
4734 | if (PrevPartial && PrevPartial->getInstantiatedFromMember()) |
4735 | PrevPartial->setMemberSpecialization(); |
4736 | |
4737 | CheckTemplatePartialSpecialization(Partial); |
4738 | } else { |
4739 | // Create a new class template specialization declaration node for |
4740 | // this explicit specialization or friend declaration. |
4741 | Specialization = VarTemplateSpecializationDecl::Create( |
4742 | Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc, |
4743 | SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC, Args: CanonicalConverted); |
4744 | Specialization->setTemplateArgsInfo(TemplateArgs); |
4745 | |
4746 | if (!PrevDecl) |
4747 | VarTemplate->AddSpecialization(D: Specialization, InsertPos); |
4748 | } |
4749 | |
4750 | // C++ [temp.expl.spec]p6: |
4751 | // If a template, a member template or the member of a class template is |
4752 | // explicitly specialized then that specialization shall be declared |
4753 | // before the first use of that specialization that would cause an implicit |
4754 | // instantiation to take place, in every translation unit in which such a |
4755 | // use occurs; no diagnostic is required. |
4756 | if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { |
4757 | bool Okay = false; |
4758 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
4759 | // Is there any previous explicit specialization declaration? |
4760 | if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) { |
4761 | Okay = true; |
4762 | break; |
4763 | } |
4764 | } |
4765 | |
4766 | if (!Okay) { |
4767 | SourceRange Range(TemplateNameLoc, RAngleLoc); |
4768 | Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) |
4769 | << Name << Range; |
4770 | |
4771 | Diag(PrevDecl->getPointOfInstantiation(), |
4772 | diag::note_instantiation_required_here) |
4773 | << (PrevDecl->getTemplateSpecializationKind() != |
4774 | TSK_ImplicitInstantiation); |
4775 | return true; |
4776 | } |
4777 | } |
4778 | |
4779 | Specialization->setTemplateKeywordLoc(TemplateKWLoc); |
4780 | Specialization->setLexicalDeclContext(CurContext); |
4781 | |
4782 | // Add the specialization into its lexical context, so that it can |
4783 | // be seen when iterating through the list of declarations in that |
4784 | // context. However, specializations are not found by name lookup. |
4785 | CurContext->addDecl(Specialization); |
4786 | |
4787 | // Note that this is an explicit specialization. |
4788 | Specialization->setSpecializationKind(TSK_ExplicitSpecialization); |
4789 | |
4790 | Previous.clear(); |
4791 | if (PrevDecl) |
4792 | Previous.addDecl(PrevDecl); |
4793 | else if (Specialization->isStaticDataMember() && |
4794 | Specialization->isOutOfLine()) |
4795 | Specialization->setAccess(VarTemplate->getAccess()); |
4796 | |
4797 | return Specialization; |
4798 | } |
4799 | |
4800 | namespace { |
4801 | /// A partial specialization whose template arguments have matched |
4802 | /// a given template-id. |
4803 | struct PartialSpecMatchResult { |
4804 | VarTemplatePartialSpecializationDecl *Partial; |
4805 | TemplateArgumentList *Args; |
4806 | }; |
4807 | } // end anonymous namespace |
4808 | |
4809 | DeclResult |
4810 | Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, |
4811 | SourceLocation TemplateNameLoc, |
4812 | const TemplateArgumentListInfo &TemplateArgs) { |
4813 | assert(Template && "A variable template id without template?" ); |
4814 | |
4815 | // Check that the template argument list is well-formed for this template. |
4816 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4817 | if (CheckTemplateArgumentList( |
4818 | Template, TemplateNameLoc, |
4819 | const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, |
4820 | SugaredConverted, CanonicalConverted, |
4821 | /*UpdateArgsWithConversions=*/true)) |
4822 | return true; |
4823 | |
4824 | // Produce a placeholder value if the specialization is dependent. |
4825 | if (Template->getDeclContext()->isDependentContext() || |
4826 | TemplateSpecializationType::anyDependentTemplateArguments( |
4827 | TemplateArgs, Converted: CanonicalConverted)) |
4828 | return DeclResult(); |
4829 | |
4830 | // Find the variable template specialization declaration that |
4831 | // corresponds to these arguments. |
4832 | void *InsertPos = nullptr; |
4833 | if (VarTemplateSpecializationDecl *Spec = |
4834 | Template->findSpecialization(Args: CanonicalConverted, InsertPos)) { |
4835 | checkSpecializationReachability(TemplateNameLoc, Spec); |
4836 | // If we already have a variable template specialization, return it. |
4837 | return Spec; |
4838 | } |
4839 | |
4840 | // This is the first time we have referenced this variable template |
4841 | // specialization. Create the canonical declaration and add it to |
4842 | // the set of specializations, based on the closest partial specialization |
4843 | // that it represents. That is, |
4844 | VarDecl *InstantiationPattern = Template->getTemplatedDecl(); |
4845 | const TemplateArgumentList *PartialSpecArgs = nullptr; |
4846 | bool AmbiguousPartialSpec = false; |
4847 | typedef PartialSpecMatchResult MatchResult; |
4848 | SmallVector<MatchResult, 4> Matched; |
4849 | SourceLocation PointOfInstantiation = TemplateNameLoc; |
4850 | TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation, |
4851 | /*ForTakingAddress=*/false); |
4852 | |
4853 | // 1. Attempt to find the closest partial specialization that this |
4854 | // specializes, if any. |
4855 | // TODO: Unify with InstantiateClassTemplateSpecialization()? |
4856 | // Perhaps better after unification of DeduceTemplateArguments() and |
4857 | // getMoreSpecializedPartialSpecialization(). |
4858 | SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
4859 | Template->getPartialSpecializations(PS&: PartialSpecs); |
4860 | |
4861 | for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { |
4862 | VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; |
4863 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
4864 | |
4865 | if (TemplateDeductionResult Result = |
4866 | DeduceTemplateArguments(Partial, TemplateArgs: CanonicalConverted, Info); |
4867 | Result != TemplateDeductionResult::Success) { |
4868 | // Store the failed-deduction information for use in diagnostics, later. |
4869 | // TODO: Actually use the failed-deduction info? |
4870 | FailedCandidates.addCandidate().set( |
4871 | Found: DeclAccessPair::make(Template, AS_public), Spec: Partial, |
4872 | Info: MakeDeductionFailureInfo(Context, TDK: Result, Info)); |
4873 | (void)Result; |
4874 | } else { |
4875 | Matched.push_back(Elt: PartialSpecMatchResult()); |
4876 | Matched.back().Partial = Partial; |
4877 | Matched.back().Args = Info.takeCanonical(); |
4878 | } |
4879 | } |
4880 | |
4881 | if (Matched.size() >= 1) { |
4882 | SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); |
4883 | if (Matched.size() == 1) { |
4884 | // -- If exactly one matching specialization is found, the |
4885 | // instantiation is generated from that specialization. |
4886 | // We don't need to do anything for this. |
4887 | } else { |
4888 | // -- If more than one matching specialization is found, the |
4889 | // partial order rules (14.5.4.2) are used to determine |
4890 | // whether one of the specializations is more specialized |
4891 | // than the others. If none of the specializations is more |
4892 | // specialized than all of the other matching |
4893 | // specializations, then the use of the variable template is |
4894 | // ambiguous and the program is ill-formed. |
4895 | for (SmallVector<MatchResult, 4>::iterator P = Best + 1, |
4896 | PEnd = Matched.end(); |
4897 | P != PEnd; ++P) { |
4898 | if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial, |
4899 | Loc: PointOfInstantiation) == |
4900 | P->Partial) |
4901 | Best = P; |
4902 | } |
4903 | |
4904 | // Determine if the best partial specialization is more specialized than |
4905 | // the others. |
4906 | for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), |
4907 | PEnd = Matched.end(); |
4908 | P != PEnd; ++P) { |
4909 | if (P != Best && getMoreSpecializedPartialSpecialization( |
4910 | PS1: P->Partial, PS2: Best->Partial, |
4911 | Loc: PointOfInstantiation) != Best->Partial) { |
4912 | AmbiguousPartialSpec = true; |
4913 | break; |
4914 | } |
4915 | } |
4916 | } |
4917 | |
4918 | // Instantiate using the best variable template partial specialization. |
4919 | InstantiationPattern = Best->Partial; |
4920 | PartialSpecArgs = Best->Args; |
4921 | } else { |
4922 | // -- If no match is found, the instantiation is generated |
4923 | // from the primary template. |
4924 | // InstantiationPattern = Template->getTemplatedDecl(); |
4925 | } |
4926 | |
4927 | // 2. Create the canonical declaration. |
4928 | // Note that we do not instantiate a definition until we see an odr-use |
4929 | // in DoMarkVarDeclReferenced(). |
4930 | // FIXME: LateAttrs et al.? |
4931 | VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( |
4932 | VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, TemplateArgsInfo: TemplateArgs, |
4933 | Converted&: CanonicalConverted, PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/); |
4934 | if (!Decl) |
4935 | return true; |
4936 | |
4937 | if (AmbiguousPartialSpec) { |
4938 | // Partial ordering did not produce a clear winner. Complain. |
4939 | Decl->setInvalidDecl(); |
4940 | Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) |
4941 | << Decl; |
4942 | |
4943 | // Print the matching partial specializations. |
4944 | for (MatchResult P : Matched) |
4945 | Diag(P.Partial->getLocation(), diag::note_partial_spec_match) |
4946 | << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(), |
4947 | *P.Args); |
4948 | return true; |
4949 | } |
4950 | |
4951 | if (VarTemplatePartialSpecializationDecl *D = |
4952 | dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern)) |
4953 | Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs); |
4954 | |
4955 | checkSpecializationReachability(TemplateNameLoc, Decl); |
4956 | |
4957 | assert(Decl && "No variable template specialization?" ); |
4958 | return Decl; |
4959 | } |
4960 | |
4961 | ExprResult |
4962 | Sema::CheckVarTemplateId(const CXXScopeSpec &SS, |
4963 | const DeclarationNameInfo &NameInfo, |
4964 | VarTemplateDecl *Template, SourceLocation TemplateLoc, |
4965 | const TemplateArgumentListInfo *TemplateArgs) { |
4966 | |
4967 | DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(), |
4968 | TemplateArgs: *TemplateArgs); |
4969 | if (Decl.isInvalid()) |
4970 | return ExprError(); |
4971 | |
4972 | if (!Decl.get()) |
4973 | return ExprResult(); |
4974 | |
4975 | VarDecl *Var = cast<VarDecl>(Val: Decl.get()); |
4976 | if (!Var->getTemplateSpecializationKind()) |
4977 | Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation, |
4978 | PointOfInstantiation: NameInfo.getLoc()); |
4979 | |
4980 | // Build an ordinary singleton decl ref. |
4981 | return BuildDeclarationNameExpr(SS, NameInfo, Var, |
4982 | /*FoundD=*/nullptr, TemplateArgs); |
4983 | } |
4984 | |
4985 | void Sema::diagnoseMissingTemplateArguments(TemplateName Name, |
4986 | SourceLocation Loc) { |
4987 | Diag(Loc, diag::err_template_missing_args) |
4988 | << (int)getTemplateNameKindForDiagnostics(Name) << Name; |
4989 | if (TemplateDecl *TD = Name.getAsTemplateDecl()) { |
4990 | NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange()); |
4991 | } |
4992 | } |
4993 | |
4994 | ExprResult |
4995 | Sema::CheckConceptTemplateId(const CXXScopeSpec &SS, |
4996 | SourceLocation TemplateKWLoc, |
4997 | const DeclarationNameInfo &ConceptNameInfo, |
4998 | NamedDecl *FoundDecl, |
4999 | ConceptDecl *NamedConcept, |
5000 | const TemplateArgumentListInfo *TemplateArgs) { |
5001 | assert(NamedConcept && "A concept template id without a template?" ); |
5002 | |
5003 | llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
5004 | if (CheckTemplateArgumentList( |
5005 | NamedConcept, ConceptNameInfo.getLoc(), |
5006 | const_cast<TemplateArgumentListInfo &>(*TemplateArgs), |
5007 | /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted, |
5008 | /*UpdateArgsWithConversions=*/false)) |
5009 | return ExprError(); |
5010 | |
5011 | auto *CSD = ImplicitConceptSpecializationDecl::Create( |
5012 | C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(), |
5013 | ConvertedArgs: CanonicalConverted); |
5014 | ConstraintSatisfaction Satisfaction; |
5015 | bool AreArgsDependent = |
5016 | TemplateSpecializationType::anyDependentTemplateArguments( |
5017 | *TemplateArgs, Converted: CanonicalConverted); |
5018 | MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted, |
5019 | /*Final=*/false); |
5020 | LocalInstantiationScope Scope(*this); |
5021 | |
5022 | EnterExpressionEvaluationContext EECtx{ |
5023 | *this, ExpressionEvaluationContext::ConstantEvaluated, CSD}; |
5024 | |
5025 | if (!AreArgsDependent && |
5026 | CheckConstraintSatisfaction( |
5027 | NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL, |
5028 | SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(), |
5029 | TemplateArgs->getRAngleLoc()), |
5030 | Satisfaction)) |
5031 | return ExprError(); |
5032 | auto *CL = ConceptReference::Create( |
5033 | C: Context, |
5034 | NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{}, |
5035 | TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept, |
5036 | ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs)); |
5037 | return ConceptSpecializationExpr::Create( |
5038 | Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction); |
5039 | } |
5040 | |
5041 | ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, |
5042 | SourceLocation TemplateKWLoc, |
5043 | LookupResult &R, |
5044 | bool RequiresADL, |
5045 | const TemplateArgumentListInfo *TemplateArgs) { |
5046 | // FIXME: Can we do any checking at this point? I guess we could check the |
5047 | // template arguments that we have against the template name, if the template |
5048 | // name refers to a single template. That's not a terribly common case, |
5049 | // though. |
5050 | // foo<int> could identify a single function unambiguously |
5051 | // This approach does NOT work, since f<int>(1); |
5052 | // gets resolved prior to resorting to overload resolution |
5053 | // i.e., template<class T> void f(double); |
5054 | // vs template<class T, class U> void f(U); |
5055 | |
5056 | // These should be filtered out by our callers. |
5057 | assert(!R.isAmbiguous() && "ambiguous lookup when building templateid" ); |
5058 | |
5059 | // Non-function templates require a template argument list. |
5060 | if (auto *TD = R.getAsSingle<TemplateDecl>()) { |
5061 | if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) { |
5062 | diagnoseMissingTemplateArguments(Name: TemplateName(TD), Loc: R.getNameLoc()); |
5063 | return ExprError(); |
5064 | } |
5065 | } |
5066 | bool KnownDependent = false; |
5067 | // In C++1y, check variable template ids. |
5068 | if (R.getAsSingle<VarTemplateDecl>()) { |
5069 | ExprResult Res = CheckVarTemplateId(SS, NameInfo: R.getLookupNameInfo(), |
5070 | Template: R.getAsSingle<VarTemplateDecl>(), |
5071 | TemplateLoc: TemplateKWLoc, TemplateArgs); |
5072 | if (Res.isInvalid() || Res.isUsable()) |
5073 | return Res; |
5074 | // Result is dependent. Carry on to build an UnresolvedLookupEpxr. |
5075 | KnownDependent = true; |
5076 | } |
5077 | |
5078 | if (R.getAsSingle<ConceptDecl>()) { |
5079 | return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(), |
5080 | FoundDecl: R.getFoundDecl(), |
5081 | NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs); |
5082 | } |
5083 | |
5084 | // We don't want lookup warnings at this point. |
5085 | R.suppressDiagnostics(); |
5086 | |
5087 | UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create( |
5088 | Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context), |
5089 | TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs, |
5090 | Begin: R.begin(), End: R.end(), KnownDependent); |
5091 | |
5092 | return ULE; |
5093 | } |
5094 | |
5095 | // We actually only call this from template instantiation. |
5096 | ExprResult |
5097 | Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, |
5098 | SourceLocation TemplateKWLoc, |
5099 | const DeclarationNameInfo &NameInfo, |
5100 | const TemplateArgumentListInfo *TemplateArgs) { |
5101 | |
5102 | assert(TemplateArgs || TemplateKWLoc.isValid()); |
5103 | DeclContext *DC; |
5104 | if (!(DC = computeDeclContext(SS, EnteringContext: false)) || |
5105 | DC->isDependentContext() || |
5106 | RequireCompleteDeclContext(SS, DC)) |
5107 | return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); |
5108 | |
5109 | bool MemberOfUnknownSpecialization; |
5110 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
5111 | if (LookupTemplateName(Found&: R, S: (Scope *)nullptr, SS, ObjectType: QualType(), |
5112 | /*Entering*/EnteringContext: false, MemberOfUnknownSpecialization, |
5113 | RequiredTemplate: TemplateKWLoc)) |
5114 | return ExprError(); |
5115 | |
5116 | if (R.isAmbiguous()) |
5117 | return ExprError(); |
5118 | |
5119 | if (R.empty()) { |
5120 | Diag(NameInfo.getLoc(), diag::err_no_member) |
5121 | << NameInfo.getName() << DC << SS.getRange(); |
5122 | return ExprError(); |
5123 | } |
5124 | |
5125 | auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp, |
5126 | bool isTypeAliasTemplateDecl) { |
5127 | Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template) |
5128 | << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange() |
5129 | << isTypeAliasTemplateDecl; |
5130 | Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0; |
5131 | return ExprError(); |
5132 | }; |
5133 | |
5134 | if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) |
5135 | return DiagnoseTypeTemplateDecl(Temp, false); |
5136 | |
5137 | if (TypeAliasTemplateDecl *Temp = R.getAsSingle<TypeAliasTemplateDecl>()) |
5138 | return DiagnoseTypeTemplateDecl(Temp, true); |
5139 | |
5140 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ RequiresADL: false, TemplateArgs); |
5141 | } |
5142 | |
5143 | /// Form a template name from a name that is syntactically required to name a |
5144 | /// template, either due to use of the 'template' keyword or because a name in |
5145 | /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4). |
5146 | /// |
5147 | /// This action forms a template name given the name of the template and its |
5148 | /// optional scope specifier. This is used when the 'template' keyword is used |
5149 | /// or when the parsing context unambiguously treats a following '<' as |
5150 | /// introducing a template argument list. Note that this may produce a |
5151 | /// non-dependent template name if we can perform the lookup now and identify |
5152 | /// the named template. |
5153 | /// |
5154 | /// For example, given "x.MetaFun::template apply", the scope specifier |
5155 | /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location |
5156 | /// of the "template" keyword, and "apply" is the \p Name. |
5157 | TemplateNameKind Sema::ActOnTemplateName(Scope *S, |
5158 | CXXScopeSpec &SS, |
5159 | SourceLocation TemplateKWLoc, |
5160 | const UnqualifiedId &Name, |
5161 | ParsedType ObjectType, |
5162 | bool EnteringContext, |
5163 | TemplateTy &Result, |
5164 | bool AllowInjectedClassName) { |
5165 | if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent()) |
5166 | Diag(TemplateKWLoc, |
5167 | getLangOpts().CPlusPlus11 ? |
5168 | diag::warn_cxx98_compat_template_outside_of_template : |
5169 | diag::ext_template_outside_of_template) |
5170 | << FixItHint::CreateRemoval(TemplateKWLoc); |
5171 | |
5172 | if (SS.isInvalid()) |
5173 | return TNK_Non_template; |
5174 | |
5175 | // Figure out where isTemplateName is going to look. |
5176 | DeclContext *LookupCtx = nullptr; |
5177 | if (SS.isNotEmpty()) |
5178 | LookupCtx = computeDeclContext(SS, EnteringContext); |
5179 | else if (ObjectType) |
5180 | LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType)); |
5181 | |
5182 | // C++0x [temp.names]p5: |
5183 | // If a name prefixed by the keyword template is not the name of |
5184 | // a template, the program is ill-formed. [Note: the keyword |
5185 | // template may not be applied to non-template members of class |
5186 | // templates. -end note ] [ Note: as is the case with the |
5187 | // typename prefix, the template prefix is allowed in cases |
5188 | // where it is not strictly necessary; i.e., when the |
5189 | // nested-name-specifier or the expression on the left of the -> |
5190 | // or . is not dependent on a template-parameter, or the use |
5191 | // does not appear in the scope of a template. -end note] |
5192 | // |
5193 | // Note: C++03 was more strict here, because it banned the use of |
5194 | // the "template" keyword prior to a template-name that was not a |
5195 | // dependent name. C++ DR468 relaxed this requirement (the |
5196 | // "template" keyword is now permitted). We follow the C++0x |
5197 | // rules, even in C++03 mode with a warning, retroactively applying the DR. |
5198 | bool MemberOfUnknownSpecialization; |
5199 | TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name, |
5200 | ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result, |
5201 | MemberOfUnknownSpecialization); |
5202 | if (TNK != TNK_Non_template) { |
5203 | // We resolved this to a (non-dependent) template name. Return it. |
5204 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx); |
5205 | if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD && |
5206 | Name.getKind() == UnqualifiedIdKind::IK_Identifier && |
5207 | Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) { |
5208 | // C++14 [class.qual]p2: |
5209 | // In a lookup in which function names are not ignored and the |
5210 | // nested-name-specifier nominates a class C, if the name specified |
5211 | // [...] is the injected-class-name of C, [...] the name is instead |
5212 | // considered to name the constructor |
5213 | // |
5214 | // We don't get here if naming the constructor would be valid, so we |
5215 | // just reject immediately and recover by treating the |
5216 | // injected-class-name as naming the template. |
5217 | Diag(Name.getBeginLoc(), |
5218 | diag::ext_out_of_line_qualified_id_type_names_constructor) |
5219 | << Name.Identifier |
5220 | << 0 /*injected-class-name used as template name*/ |
5221 | << TemplateKWLoc.isValid(); |
5222 | } |
5223 | return TNK; |
5224 | } |
5225 | |
5226 | if (!MemberOfUnknownSpecialization) { |
5227 | // Didn't find a template name, and the lookup wasn't dependent. |
5228 | // Do the lookup again to determine if this is a "nothing found" case or |
5229 | // a "not a template" case. FIXME: Refactor isTemplateName so we don't |
5230 | // need to do this. |
5231 | DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name); |
5232 | LookupResult R(*this, DNI.getName(), Name.getBeginLoc(), |
5233 | LookupOrdinaryName); |
5234 | bool MOUS; |
5235 | // Tell LookupTemplateName that we require a template so that it diagnoses |
5236 | // cases where it finds a non-template. |
5237 | RequiredTemplateKind RTK = TemplateKWLoc.isValid() |
5238 | ? RequiredTemplateKind(TemplateKWLoc) |
5239 | : TemplateNameIsRequired; |
5240 | if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, MemberOfUnknownSpecialization&: MOUS, |
5241 | RequiredTemplate: RTK, ATK: nullptr, /*AllowTypoCorrection=*/false) && |
5242 | !R.isAmbiguous()) { |
5243 | if (LookupCtx) |
5244 | Diag(Name.getBeginLoc(), diag::err_no_member) |
5245 | << DNI.getName() << LookupCtx << SS.getRange(); |
5246 | else |
5247 | Diag(Name.getBeginLoc(), diag::err_undeclared_use) |
5248 | << DNI.getName() << SS.getRange(); |
5249 | } |
5250 | return TNK_Non_template; |
5251 | } |
5252 | |
5253 | NestedNameSpecifier *Qualifier = SS.getScopeRep(); |
5254 | |
5255 | switch (Name.getKind()) { |
5256 | case UnqualifiedIdKind::IK_Identifier: |
5257 | Result = TemplateTy::make( |
5258 | P: Context.getDependentTemplateName(NNS: Qualifier, Name: Name.Identifier)); |
5259 | return TNK_Dependent_template_name; |
5260 | |
5261 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
5262 | Result = TemplateTy::make(P: Context.getDependentTemplateName( |
5263 | NNS: Qualifier, Operator: Name.OperatorFunctionId.Operator)); |
5264 | return TNK_Function_template; |
5265 | |
5266 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
5267 | // This is a kind of template name, but can never occur in a dependent |
5268 | // scope (literal operators can only be declared at namespace scope). |
5269 | break; |
5270 | |
5271 | default: |
5272 | break; |
5273 | } |
5274 | |
5275 | // This name cannot possibly name a dependent template. Diagnose this now |
5276 | // rather than building a dependent template name that can never be valid. |
5277 | Diag(Name.getBeginLoc(), |
5278 | diag::err_template_kw_refers_to_dependent_non_template) |
5279 | << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange() |
5280 | << TemplateKWLoc.isValid() << TemplateKWLoc; |
5281 | return TNK_Non_template; |
5282 | } |
5283 | |
5284 | bool Sema::CheckTemplateTypeArgument( |
5285 | TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL, |
5286 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
5287 | SmallVectorImpl<TemplateArgument> &CanonicalConverted) { |
5288 | const TemplateArgument &Arg = AL.getArgument(); |
5289 | QualType ArgType; |
5290 | TypeSourceInfo *TSI = nullptr; |
5291 | |
5292 | // Check template type parameter. |
5293 | switch(Arg.getKind()) { |
5294 | case TemplateArgument::Type: |
5295 | // C++ [temp.arg.type]p1: |
5296 | // A template-argument for a template-parameter which is a |
5297 | // type shall be a type-id. |
5298 | ArgType = Arg.getAsType(); |
5299 | TSI = AL.getTypeSourceInfo(); |
5300 | break; |
5301 | case TemplateArgument::Template: |
5302 | case TemplateArgument::TemplateExpansion: { |
5303 | // We have a template type parameter but the template argument |
5304 | // is a template without any arguments. |
5305 | SourceRange SR = AL.getSourceRange(); |
5306 | TemplateName Name = Arg.getAsTemplateOrTemplatePattern(); |
5307 | diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd()); |
5308 | return true; |
5309 | } |
5310 | case TemplateArgument::Expression: { |
5311 | // We have a template type parameter but the template argument is an |
5312 | // expression; see if maybe it is missing the "typename" keyword. |
5313 | CXXScopeSpec SS; |
5314 | DeclarationNameInfo NameInfo; |
5315 | |
5316 | if (DependentScopeDeclRefExpr *ArgExpr = |
5317 | dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) { |
5318 | SS.Adopt(Other: ArgExpr->getQualifierLoc()); |
5319 | NameInfo = ArgExpr->getNameInfo(); |
5320 | } else if (CXXDependentScopeMemberExpr *ArgExpr = |
5321 | dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) { |
5322 | if (ArgExpr->isImplicitAccess()) { |
5323 | SS.Adopt(Other: ArgExpr->getQualifierLoc()); |
5324 | NameInfo = ArgExpr->getMemberNameInfo(); |
5325 | } |
5326 | } |
5327 | |
5328 | if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { |
5329 | LookupResult Result(*this, NameInfo, LookupOrdinaryName); |
5330 | LookupParsedName(R&: Result, S: CurScope, SS: &SS); |
5331 | |
5332 | if (Result.getAsSingle<TypeDecl>() || |
5333 | Result.getResultKind() == |
5334 | LookupResult::NotFoundInCurrentInstantiation) { |
5335 | assert(SS.getScopeRep() && "dependent scope expr must has a scope!" ); |
5336 | // Suggest that the user add 'typename' before the NNS. |
5337 | SourceLocation Loc = AL.getSourceRange().getBegin(); |
5338 | Diag(Loc, getLangOpts().MSVCCompat |
5339 | ? diag::ext_ms_template_type_arg_missing_typename |
5340 | : diag::err_template_arg_must_be_type_suggest) |
5341 | << FixItHint::CreateInsertion(Loc, "typename " ); |
5342 | NoteTemplateParameterLocation(*Param); |
5343 | |
5344 | // Recover by synthesizing a type using the location information that we |
5345 | // already have. |
5346 | ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::Typename, |
5347 | NNS: SS.getScopeRep(), Name: II); |
5348 | TypeLocBuilder TLB; |
5349 | DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType); |
5350 | TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/)); |
5351 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
5352 | TL.setNameLoc(NameInfo.getLoc()); |
5353 | TSI = TLB.getTypeSourceInfo(Context, T: ArgType); |
5354 | |
5355 | // Overwrite our input TemplateArgumentLoc so that we can recover |
5356 | // properly. |
5357 | AL = TemplateArgumentLoc(TemplateArgument(ArgType), |
5358 | TemplateArgumentLocInfo(TSI)); |
5359 | |
5360 | break; |
5361 | } |
5362 | } |
5363 | // fallthrough |
5364 | [[fallthrough]]; |
5365 | } |
5366 | default: { |
5367 | // We have a template type parameter but the template argument |
5368 | // is not a type. |
5369 | SourceRange SR = AL.getSourceRange(); |
5370 | Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; |
5371 | NoteTemplateParameterLocation(*Param); |
5372 | |
5373 | return true; |
5374 | } |
5375 | } |
5376 | |
5377 | if (CheckTemplateArgument(Arg: TSI)) |
5378 | return true; |
5379 | |
5380 | // Objective-C ARC: |
5381 | // If an explicitly-specified template argument type is a lifetime type |
5382 | // with no lifetime qualifier, the __strong lifetime qualifier is inferred. |
5383 | if (getLangOpts().ObjCAutoRefCount && |
5384 | ArgType->isObjCLifetimeType() && |
5385 | !ArgType.getObjCLifetime()) { |
5386 | Qualifiers Qs; |
5387 | Qs.setObjCLifetime(Qualifiers::OCL_Strong); |
5388 | ArgType = Context.getQualifiedType(T: ArgType, Qs); |
5389 | } |
5390 | |
5391 | SugaredConverted.push_back(Elt: TemplateArgument(ArgType)); |
5392 | CanonicalConverted.push_back( |
5393 | Elt: TemplateArgument(Context.getCanonicalType(T: ArgType))); |
5394 | return false; |
5395 | } |
5396 | |
5397 | /// Substitute template arguments into the default template argument for |
5398 | /// the given template type parameter. |
5399 | /// |
5400 | /// \param SemaRef the semantic analysis object for which we are performing |
5401 | /// the substitution. |
5402 | /// |
5403 | /// \param Template the template that we are synthesizing template arguments |
5404 | /// for. |
5405 | /// |
5406 | /// \param TemplateLoc the location of the template name that started the |
5407 | /// template-id we are checking. |
5408 | /// |
5409 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
5410 | /// terminates the template-id. |
5411 | /// |
5412 | /// \param Param the template template parameter whose default we are |
5413 | /// substituting into. |
5414 | /// |
5415 | /// \param Converted the list of template arguments provided for template |
5416 | /// parameters that precede \p Param in the template parameter list. |
5417 | /// \returns the substituted template argument, or NULL if an error occurred. |
5418 | static TypeSourceInfo *SubstDefaultTemplateArgument( |
5419 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
5420 | SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, |
5421 | ArrayRef<TemplateArgument> SugaredConverted, |
5422 | ArrayRef<TemplateArgument> CanonicalConverted) { |
5423 | TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); |
5424 | |
5425 | // If the argument type is dependent, instantiate it now based |
5426 | // on the previously-computed template arguments. |
5427 | if (ArgType->getType()->isInstantiationDependentType()) { |
5428 | Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, |
5429 | SugaredConverted, |
5430 | SourceRange(TemplateLoc, RAngleLoc)); |
5431 | if (Inst.isInvalid()) |
5432 | return nullptr; |
5433 | |
5434 | // Only substitute for the innermost template argument list. |
5435 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
5436 | /*Final=*/true); |
5437 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
5438 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
5439 | |
5440 | bool ForLambdaCallOperator = false; |
5441 | if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext())) |
5442 | ForLambdaCallOperator = Rec->isLambda(); |
5443 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(), |
5444 | !ForLambdaCallOperator); |
5445 | ArgType = |
5446 | SemaRef.SubstType(ArgType, TemplateArgLists, |
5447 | Param->getDefaultArgumentLoc(), Param->getDeclName()); |
5448 | } |
5449 | |
5450 | return ArgType; |
5451 | } |
5452 | |
5453 | /// Substitute template arguments into the default template argument for |
5454 | /// the given non-type template parameter. |
5455 | /// |
5456 | /// \param SemaRef the semantic analysis object for which we are performing |
5457 | /// the substitution. |
5458 | /// |
5459 | /// \param Template the template that we are synthesizing template arguments |
5460 | /// for. |
5461 | /// |
5462 | /// \param TemplateLoc the location of the template name that started the |
5463 | /// template-id we are checking. |
5464 | /// |
5465 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
5466 | /// terminates the template-id. |
5467 | /// |
5468 | /// \param Param the non-type template parameter whose default we are |
5469 | /// substituting into. |
5470 | /// |
5471 | /// \param Converted the list of template arguments provided for template |
5472 | /// parameters that precede \p Param in the template parameter list. |
5473 | /// |
5474 | /// \returns the substituted template argument, or NULL if an error occurred. |
5475 | static ExprResult SubstDefaultTemplateArgument( |
5476 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
5477 | SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param, |
5478 | ArrayRef<TemplateArgument> SugaredConverted, |
5479 | ArrayRef<TemplateArgument> CanonicalConverted) { |
5480 | Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, |
5481 | SugaredConverted, |
5482 | SourceRange(TemplateLoc, RAngleLoc)); |
5483 | if (Inst.isInvalid()) |
5484 | return ExprError(); |
5485 | |
5486 | // Only substitute for the innermost template argument list. |
5487 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
5488 | /*Final=*/true); |
5489 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
5490 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
5491 | |
5492 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); |
5493 | EnterExpressionEvaluationContext ConstantEvaluated( |
5494 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
5495 | return SemaRef.SubstExpr(E: Param->getDefaultArgument(), TemplateArgs: TemplateArgLists); |
5496 | } |
5497 | |
5498 | /// Substitute template arguments into the default template argument for |
5499 | /// the given template template parameter. |
5500 | /// |
5501 | /// \param SemaRef the semantic analysis object for which we are performing |
5502 | /// the substitution. |
5503 | /// |
5504 | /// \param Template the template that we are synthesizing template arguments |
5505 | /// for. |
5506 | /// |
5507 | /// \param TemplateLoc the location of the template name that started the |
5508 | /// template-id we are checking. |
5509 | /// |
5510 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
5511 | /// terminates the template-id. |
5512 | /// |
5513 | /// \param Param the template template parameter whose default we are |
5514 | /// substituting into. |
5515 | /// |
5516 | /// \param Converted the list of template arguments provided for template |
5517 | /// parameters that precede \p Param in the template parameter list. |
5518 | /// |
5519 | /// \param QualifierLoc Will be set to the nested-name-specifier (with |
5520 | /// source-location information) that precedes the template name. |
5521 | /// |
5522 | /// \returns the substituted template argument, or NULL if an error occurred. |
5523 | static TemplateName SubstDefaultTemplateArgument( |
5524 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
5525 | SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param, |
5526 | ArrayRef<TemplateArgument> SugaredConverted, |
5527 | ArrayRef<TemplateArgument> CanonicalConverted, |
5528 | NestedNameSpecifierLoc &QualifierLoc) { |
5529 | Sema::InstantiatingTemplate Inst( |
5530 | SemaRef, TemplateLoc, TemplateParameter(Param), Template, |
5531 | SugaredConverted, SourceRange(TemplateLoc, RAngleLoc)); |
5532 | if (Inst.isInvalid()) |
5533 | return TemplateName(); |
5534 | |
5535 | // Only substitute for the innermost template argument list. |
5536 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
5537 | /*Final=*/true); |
5538 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
5539 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
5540 | |
5541 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); |
5542 | // Substitute into the nested-name-specifier first, |
5543 | QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); |
5544 | if (QualifierLoc) { |
5545 | QualifierLoc = |
5546 | SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs: TemplateArgLists); |
5547 | if (!QualifierLoc) |
5548 | return TemplateName(); |
5549 | } |
5550 | |
5551 | return SemaRef.SubstTemplateName( |
5552 | QualifierLoc, |
5553 | Name: Param->getDefaultArgument().getArgument().getAsTemplate(), |
5554 | Loc: Param->getDefaultArgument().getTemplateNameLoc(), |
5555 | TemplateArgs: TemplateArgLists); |
5556 | } |
5557 | |
5558 | /// If the given template parameter has a default template |
5559 | /// argument, substitute into that default template argument and |
5560 | /// return the corresponding template argument. |
5561 | TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable( |
5562 | TemplateDecl *Template, SourceLocation TemplateLoc, |
5563 | SourceLocation RAngleLoc, Decl *Param, |
5564 | ArrayRef<TemplateArgument> SugaredConverted, |
5565 | ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) { |
5566 | HasDefaultArg = false; |
5567 | |
5568 | if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) { |
5569 | if (!hasReachableDefaultArgument(TypeParm)) |
5570 | return TemplateArgumentLoc(); |
5571 | |
5572 | HasDefaultArg = true; |
5573 | TypeSourceInfo *DI = SubstDefaultTemplateArgument( |
5574 | SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TypeParm, SugaredConverted, |
5575 | CanonicalConverted); |
5576 | if (DI) |
5577 | return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); |
5578 | |
5579 | return TemplateArgumentLoc(); |
5580 | } |
5581 | |
5582 | if (NonTypeTemplateParmDecl *NonTypeParm |
5583 | = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) { |
5584 | if (!hasReachableDefaultArgument(NonTypeParm)) |
5585 | return TemplateArgumentLoc(); |
5586 | |
5587 | HasDefaultArg = true; |
5588 | ExprResult Arg = SubstDefaultTemplateArgument( |
5589 | SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: NonTypeParm, SugaredConverted, |
5590 | CanonicalConverted); |
5591 | if (Arg.isInvalid()) |
5592 | return TemplateArgumentLoc(); |
5593 | |
5594 | Expr *ArgE = Arg.getAs<Expr>(); |
5595 | return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); |
5596 | } |
5597 | |
5598 | TemplateTemplateParmDecl *TempTempParm |
5599 | = cast<TemplateTemplateParmDecl>(Val: Param); |
5600 | if (!hasReachableDefaultArgument(TempTempParm)) |
5601 | return TemplateArgumentLoc(); |
5602 | |
5603 | HasDefaultArg = true; |
5604 | NestedNameSpecifierLoc QualifierLoc; |
5605 | TemplateName TName = SubstDefaultTemplateArgument( |
5606 | SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TempTempParm, SugaredConverted, |
5607 | CanonicalConverted, QualifierLoc); |
5608 | if (TName.isNull()) |
5609 | return TemplateArgumentLoc(); |
5610 | |
5611 | return TemplateArgumentLoc( |
5612 | Context, TemplateArgument(TName), |
5613 | TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), |
5614 | TempTempParm->getDefaultArgument().getTemplateNameLoc()); |
5615 | } |
5616 | |
5617 | /// Convert a template-argument that we parsed as a type into a template, if |
5618 | /// possible. C++ permits injected-class-names to perform dual service as |
5619 | /// template template arguments and as template type arguments. |
5620 | static TemplateArgumentLoc |
5621 | convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) { |
5622 | // Extract and step over any surrounding nested-name-specifier. |
5623 | NestedNameSpecifierLoc QualLoc; |
5624 | if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) { |
5625 | if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None) |
5626 | return TemplateArgumentLoc(); |
5627 | |
5628 | QualLoc = ETLoc.getQualifierLoc(); |
5629 | TLoc = ETLoc.getNamedTypeLoc(); |
5630 | } |
5631 | // If this type was written as an injected-class-name, it can be used as a |
5632 | // template template argument. |
5633 | if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>()) |
5634 | return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(), |
5635 | QualLoc, InjLoc.getNameLoc()); |
5636 | |
5637 | // If this type was written as an injected-class-name, it may have been |
5638 | // converted to a RecordType during instantiation. If the RecordType is |
5639 | // *not* wrapped in a TemplateSpecializationType and denotes a class |
5640 | // template specialization, it must have come from an injected-class-name. |
5641 | if (auto RecLoc = TLoc.getAs<RecordTypeLoc>()) |
5642 | if (auto *CTSD = |
5643 | dyn_cast<ClassTemplateSpecializationDecl>(Val: RecLoc.getDecl())) |
5644 | return TemplateArgumentLoc(Context, |
5645 | TemplateName(CTSD->getSpecializedTemplate()), |
5646 | QualLoc, RecLoc.getNameLoc()); |
5647 | |
5648 | return TemplateArgumentLoc(); |
5649 | } |
5650 | |
5651 | /// Check that the given template argument corresponds to the given |
5652 | /// template parameter. |
5653 | /// |
5654 | /// \param Param The template parameter against which the argument will be |
5655 | /// checked. |
5656 | /// |
5657 | /// \param Arg The template argument, which may be updated due to conversions. |
5658 | /// |
5659 | /// \param Template The template in which the template argument resides. |
5660 | /// |
5661 | /// \param TemplateLoc The location of the template name for the template |
5662 | /// whose argument list we're matching. |
5663 | /// |
5664 | /// \param RAngleLoc The location of the right angle bracket ('>') that closes |
5665 | /// the template argument list. |
5666 | /// |
5667 | /// \param ArgumentPackIndex The index into the argument pack where this |
5668 | /// argument will be placed. Only valid if the parameter is a parameter pack. |
5669 | /// |
5670 | /// \param Converted The checked, converted argument will be added to the |
5671 | /// end of this small vector. |
5672 | /// |
5673 | /// \param CTAK Describes how we arrived at this particular template argument: |
5674 | /// explicitly written, deduced, etc. |
5675 | /// |
5676 | /// \returns true on error, false otherwise. |
5677 | bool Sema::CheckTemplateArgument( |
5678 | NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, |
5679 | SourceLocation TemplateLoc, SourceLocation RAngleLoc, |
5680 | unsigned ArgumentPackIndex, |
5681 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
5682 | SmallVectorImpl<TemplateArgument> &CanonicalConverted, |
5683 | CheckTemplateArgumentKind CTAK) { |
5684 | // Check template type parameters. |
5685 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) |
5686 | return CheckTemplateTypeArgument(Param: TTP, AL&: Arg, SugaredConverted, |
5687 | CanonicalConverted); |
5688 | |
5689 | // Check non-type template parameters. |
5690 | if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) { |
5691 | // Do substitution on the type of the non-type template parameter |
5692 | // with the template arguments we've seen thus far. But if the |
5693 | // template has a dependent context then we cannot substitute yet. |
5694 | QualType NTTPType = NTTP->getType(); |
5695 | if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) |
5696 | NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex); |
5697 | |
5698 | if (NTTPType->isInstantiationDependentType() && |
5699 | !isa<TemplateTemplateParmDecl>(Val: Template) && |
5700 | !Template->getDeclContext()->isDependentContext()) { |
5701 | // Do substitution on the type of the non-type template parameter. |
5702 | InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP, |
5703 | SugaredConverted, |
5704 | SourceRange(TemplateLoc, RAngleLoc)); |
5705 | if (Inst.isInvalid()) |
5706 | return true; |
5707 | |
5708 | MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted, |
5709 | /*Final=*/true); |
5710 | // If the parameter is a pack expansion, expand this slice of the pack. |
5711 | if (auto *PET = NTTPType->getAs<PackExpansionType>()) { |
5712 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, |
5713 | ArgumentPackIndex); |
5714 | NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(), |
5715 | NTTP->getDeclName()); |
5716 | } else { |
5717 | NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(), |
5718 | NTTP->getDeclName()); |
5719 | } |
5720 | |
5721 | // If that worked, check the non-type template parameter type |
5722 | // for validity. |
5723 | if (!NTTPType.isNull()) |
5724 | NTTPType = CheckNonTypeTemplateParameterType(NTTPType, |
5725 | NTTP->getLocation()); |
5726 | if (NTTPType.isNull()) |
5727 | return true; |
5728 | } |
5729 | |
5730 | switch (Arg.getArgument().getKind()) { |
5731 | case TemplateArgument::Null: |
5732 | llvm_unreachable("Should never see a NULL template argument here" ); |
5733 | |
5734 | case TemplateArgument::Expression: { |
5735 | Expr *E = Arg.getArgument().getAsExpr(); |
5736 | TemplateArgument SugaredResult, CanonicalResult; |
5737 | unsigned CurSFINAEErrors = NumSFINAEErrors; |
5738 | ExprResult Res = CheckTemplateArgument(Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, |
5739 | CanonicalConverted&: CanonicalResult, CTAK); |
5740 | if (Res.isInvalid()) |
5741 | return true; |
5742 | // If the current template argument causes an error, give up now. |
5743 | if (CurSFINAEErrors < NumSFINAEErrors) |
5744 | return true; |
5745 | |
5746 | // If the resulting expression is new, then use it in place of the |
5747 | // old expression in the template argument. |
5748 | if (Res.get() != E) { |
5749 | TemplateArgument TA(Res.get()); |
5750 | Arg = TemplateArgumentLoc(TA, Res.get()); |
5751 | } |
5752 | |
5753 | SugaredConverted.push_back(Elt: SugaredResult); |
5754 | CanonicalConverted.push_back(Elt: CanonicalResult); |
5755 | break; |
5756 | } |
5757 | |
5758 | case TemplateArgument::Declaration: |
5759 | case TemplateArgument::Integral: |
5760 | case TemplateArgument::StructuralValue: |
5761 | case TemplateArgument::NullPtr: |
5762 | // We've already checked this template argument, so just copy |
5763 | // it to the list of converted arguments. |
5764 | SugaredConverted.push_back(Elt: Arg.getArgument()); |
5765 | CanonicalConverted.push_back( |
5766 | Elt: Context.getCanonicalTemplateArgument(Arg: Arg.getArgument())); |
5767 | break; |
5768 | |
5769 | case TemplateArgument::Template: |
5770 | case TemplateArgument::TemplateExpansion: |
5771 | // We were given a template template argument. It may not be ill-formed; |
5772 | // see below. |
5773 | if (DependentTemplateName *DTN |
5774 | = Arg.getArgument().getAsTemplateOrTemplatePattern() |
5775 | .getAsDependentTemplateName()) { |
5776 | // We have a template argument such as \c T::template X, which we |
5777 | // parsed as a template template argument. However, since we now |
5778 | // know that we need a non-type template argument, convert this |
5779 | // template name into an expression. |
5780 | |
5781 | DeclarationNameInfo NameInfo(DTN->getIdentifier(), |
5782 | Arg.getTemplateNameLoc()); |
5783 | |
5784 | CXXScopeSpec SS; |
5785 | SS.Adopt(Other: Arg.getTemplateQualifierLoc()); |
5786 | // FIXME: the template-template arg was a DependentTemplateName, |
5787 | // so it was provided with a template keyword. However, its source |
5788 | // location is not stored in the template argument structure. |
5789 | SourceLocation TemplateKWLoc; |
5790 | ExprResult E = DependentScopeDeclRefExpr::Create( |
5791 | Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, |
5792 | TemplateArgs: nullptr); |
5793 | |
5794 | // If we parsed the template argument as a pack expansion, create a |
5795 | // pack expansion expression. |
5796 | if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ |
5797 | E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: Arg.getTemplateEllipsisLoc()); |
5798 | if (E.isInvalid()) |
5799 | return true; |
5800 | } |
5801 | |
5802 | TemplateArgument SugaredResult, CanonicalResult; |
5803 | E = CheckTemplateArgument(Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, |
5804 | CanonicalConverted&: CanonicalResult, CTAK: CTAK_Specified); |
5805 | if (E.isInvalid()) |
5806 | return true; |
5807 | |
5808 | SugaredConverted.push_back(Elt: SugaredResult); |
5809 | CanonicalConverted.push_back(Elt: CanonicalResult); |
5810 | break; |
5811 | } |
5812 | |
5813 | // We have a template argument that actually does refer to a class |
5814 | // template, alias template, or template template parameter, and |
5815 | // therefore cannot be a non-type template argument. |
5816 | Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) |
5817 | << Arg.getSourceRange(); |
5818 | NoteTemplateParameterLocation(Decl: *Param); |
5819 | |
5820 | return true; |
5821 | |
5822 | case TemplateArgument::Type: { |
5823 | // We have a non-type template parameter but the template |
5824 | // argument is a type. |
5825 | |
5826 | // C++ [temp.arg]p2: |
5827 | // In a template-argument, an ambiguity between a type-id and |
5828 | // an expression is resolved to a type-id, regardless of the |
5829 | // form of the corresponding template-parameter. |
5830 | // |
5831 | // We warn specifically about this case, since it can be rather |
5832 | // confusing for users. |
5833 | QualType T = Arg.getArgument().getAsType(); |
5834 | SourceRange SR = Arg.getSourceRange(); |
5835 | if (T->isFunctionType()) |
5836 | Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; |
5837 | else |
5838 | Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; |
5839 | NoteTemplateParameterLocation(Decl: *Param); |
5840 | return true; |
5841 | } |
5842 | |
5843 | case TemplateArgument::Pack: |
5844 | llvm_unreachable("Caller must expand template argument packs" ); |
5845 | } |
5846 | |
5847 | return false; |
5848 | } |
5849 | |
5850 | |
5851 | // Check template template parameters. |
5852 | TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param); |
5853 | |
5854 | TemplateParameterList *Params = TempParm->getTemplateParameters(); |
5855 | if (TempParm->isExpandedParameterPack()) |
5856 | Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex); |
5857 | |
5858 | // Substitute into the template parameter list of the template |
5859 | // template parameter, since previously-supplied template arguments |
5860 | // may appear within the template template parameter. |
5861 | // |
5862 | // FIXME: Skip this if the parameters aren't instantiation-dependent. |
5863 | { |
5864 | // Set up a template instantiation context. |
5865 | LocalInstantiationScope Scope(*this); |
5866 | InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm, |
5867 | SugaredConverted, |
5868 | SourceRange(TemplateLoc, RAngleLoc)); |
5869 | if (Inst.isInvalid()) |
5870 | return true; |
5871 | |
5872 | Params = |
5873 | SubstTemplateParams(Params, Owner: CurContext, |
5874 | TemplateArgs: MultiLevelTemplateArgumentList( |
5875 | Template, SugaredConverted, /*Final=*/true), |
5876 | /*EvaluateConstraints=*/false); |
5877 | if (!Params) |
5878 | return true; |
5879 | } |
5880 | |
5881 | // C++1z [temp.local]p1: (DR1004) |
5882 | // When [the injected-class-name] is used [...] as a template-argument for |
5883 | // a template template-parameter [...] it refers to the class template |
5884 | // itself. |
5885 | if (Arg.getArgument().getKind() == TemplateArgument::Type) { |
5886 | TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate( |
5887 | Context, TLoc: Arg.getTypeSourceInfo()->getTypeLoc()); |
5888 | if (!ConvertedArg.getArgument().isNull()) |
5889 | Arg = ConvertedArg; |
5890 | } |
5891 | |
5892 | switch (Arg.getArgument().getKind()) { |
5893 | case TemplateArgument::Null: |
5894 | llvm_unreachable("Should never see a NULL template argument here" ); |
5895 | |
5896 | case TemplateArgument::Template: |
5897 | case TemplateArgument::TemplateExpansion: |
5898 | if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg)) |
5899 | return true; |
5900 | |
5901 | SugaredConverted.push_back(Elt: Arg.getArgument()); |
5902 | CanonicalConverted.push_back( |
5903 | Elt: Context.getCanonicalTemplateArgument(Arg: Arg.getArgument())); |
5904 | break; |
5905 | |
5906 | case TemplateArgument::Expression: |
5907 | case TemplateArgument::Type: |
5908 | // We have a template template parameter but the template |
5909 | // argument does not refer to a template. |
5910 | Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) |
5911 | << getLangOpts().CPlusPlus11; |
5912 | return true; |
5913 | |
5914 | case TemplateArgument::Declaration: |
5915 | case TemplateArgument::Integral: |
5916 | case TemplateArgument::StructuralValue: |
5917 | case TemplateArgument::NullPtr: |
5918 | llvm_unreachable("non-type argument with template template parameter" ); |
5919 | |
5920 | case TemplateArgument::Pack: |
5921 | llvm_unreachable("Caller must expand template argument packs" ); |
5922 | } |
5923 | |
5924 | return false; |
5925 | } |
5926 | |
5927 | /// Diagnose a missing template argument. |
5928 | template<typename TemplateParmDecl> |
5929 | static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, |
5930 | TemplateDecl *TD, |
5931 | const TemplateParmDecl *D, |
5932 | TemplateArgumentListInfo &Args) { |
5933 | // Dig out the most recent declaration of the template parameter; there may be |
5934 | // declarations of the template that are more recent than TD. |
5935 | D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl()) |
5936 | ->getTemplateParameters() |
5937 | ->getParam(D->getIndex())); |
5938 | |
5939 | // If there's a default argument that's not reachable, diagnose that we're |
5940 | // missing a module import. |
5941 | llvm::SmallVector<Module*, 8> Modules; |
5942 | if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) { |
5943 | S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD), |
5944 | D->getDefaultArgumentLoc(), Modules, |
5945 | Sema::MissingImportKind::DefaultArgument, |
5946 | /*Recover*/true); |
5947 | return true; |
5948 | } |
5949 | |
5950 | // FIXME: If there's a more recent default argument that *is* visible, |
5951 | // diagnose that it was declared too late. |
5952 | |
5953 | TemplateParameterList *Params = TD->getTemplateParameters(); |
5954 | |
5955 | S.Diag(Loc, diag::err_template_arg_list_different_arity) |
5956 | << /*not enough args*/0 |
5957 | << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD)) |
5958 | << TD; |
5959 | S.NoteTemplateLocation(*TD, Params->getSourceRange()); |
5960 | return true; |
5961 | } |
5962 | |
5963 | /// Check that the given template argument list is well-formed |
5964 | /// for specializing the given template. |
5965 | bool Sema::CheckTemplateArgumentList( |
5966 | TemplateDecl *Template, SourceLocation TemplateLoc, |
5967 | TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, |
5968 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
5969 | SmallVectorImpl<TemplateArgument> &CanonicalConverted, |
5970 | bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) { |
5971 | |
5972 | if (ConstraintsNotSatisfied) |
5973 | *ConstraintsNotSatisfied = false; |
5974 | |
5975 | // Make a copy of the template arguments for processing. Only make the |
5976 | // changes at the end when successful in matching the arguments to the |
5977 | // template. |
5978 | TemplateArgumentListInfo NewArgs = TemplateArgs; |
5979 | |
5980 | TemplateParameterList *Params = GetTemplateParameterList(TD: Template); |
5981 | |
5982 | SourceLocation RAngleLoc = NewArgs.getRAngleLoc(); |
5983 | |
5984 | // C++ [temp.arg]p1: |
5985 | // [...] The type and form of each template-argument specified in |
5986 | // a template-id shall match the type and form specified for the |
5987 | // corresponding parameter declared by the template in its |
5988 | // template-parameter-list. |
5989 | bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template); |
5990 | SmallVector<TemplateArgument, 2> SugaredArgumentPack; |
5991 | SmallVector<TemplateArgument, 2> CanonicalArgumentPack; |
5992 | unsigned ArgIdx = 0, NumArgs = NewArgs.size(); |
5993 | LocalInstantiationScope InstScope(*this, true); |
5994 | for (TemplateParameterList::iterator Param = Params->begin(), |
5995 | ParamEnd = Params->end(); |
5996 | Param != ParamEnd; /* increment in loop */) { |
5997 | // If we have an expanded parameter pack, make sure we don't have too |
5998 | // many arguments. |
5999 | if (std::optional<unsigned> Expansions = getExpandedPackSize(Param: *Param)) { |
6000 | if (*Expansions == SugaredArgumentPack.size()) { |
6001 | // We're done with this parameter pack. Pack up its arguments and add |
6002 | // them to the list. |
6003 | SugaredConverted.push_back( |
6004 | Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack)); |
6005 | SugaredArgumentPack.clear(); |
6006 | |
6007 | CanonicalConverted.push_back( |
6008 | Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack)); |
6009 | CanonicalArgumentPack.clear(); |
6010 | |
6011 | // This argument is assigned to the next parameter. |
6012 | ++Param; |
6013 | continue; |
6014 | } else if (ArgIdx == NumArgs && !PartialTemplateArgs) { |
6015 | // Not enough arguments for this parameter pack. |
6016 | Diag(TemplateLoc, diag::err_template_arg_list_different_arity) |
6017 | << /*not enough args*/0 |
6018 | << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) |
6019 | << Template; |
6020 | NoteTemplateLocation(*Template, Params->getSourceRange()); |
6021 | return true; |
6022 | } |
6023 | } |
6024 | |
6025 | if (ArgIdx < NumArgs) { |
6026 | // Check the template argument we were given. |
6027 | if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc, |
6028 | RAngleLoc, SugaredArgumentPack.size(), |
6029 | SugaredConverted, CanonicalConverted, |
6030 | CTAK_Specified)) |
6031 | return true; |
6032 | |
6033 | CanonicalConverted.back().setIsDefaulted( |
6034 | clang::isSubstitutedDefaultArgument( |
6035 | Ctx&: Context, Arg: NewArgs[ArgIdx].getArgument(), Param: *Param, |
6036 | Args: CanonicalConverted, Depth: Params->getDepth())); |
6037 | |
6038 | bool PackExpansionIntoNonPack = |
6039 | NewArgs[ArgIdx].getArgument().isPackExpansion() && |
6040 | (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param)); |
6041 | if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Val: Template) || |
6042 | isa<ConceptDecl>(Val: Template))) { |
6043 | // Core issue 1430: we have a pack expansion as an argument to an |
6044 | // alias template, and it's not part of a parameter pack. This |
6045 | // can't be canonicalized, so reject it now. |
6046 | // As for concepts - we cannot normalize constraints where this |
6047 | // situation exists. |
6048 | Diag(NewArgs[ArgIdx].getLocation(), |
6049 | diag::err_template_expansion_into_fixed_list) |
6050 | << (isa<ConceptDecl>(Template) ? 1 : 0) |
6051 | << NewArgs[ArgIdx].getSourceRange(); |
6052 | NoteTemplateParameterLocation(Decl: **Param); |
6053 | return true; |
6054 | } |
6055 | |
6056 | // We're now done with this argument. |
6057 | ++ArgIdx; |
6058 | |
6059 | if ((*Param)->isTemplateParameterPack()) { |
6060 | // The template parameter was a template parameter pack, so take the |
6061 | // deduced argument and place it on the argument pack. Note that we |
6062 | // stay on the same template parameter so that we can deduce more |
6063 | // arguments. |
6064 | SugaredArgumentPack.push_back(Elt: SugaredConverted.pop_back_val()); |
6065 | CanonicalArgumentPack.push_back(Elt: CanonicalConverted.pop_back_val()); |
6066 | } else { |
6067 | // Move to the next template parameter. |
6068 | ++Param; |
6069 | } |
6070 | |
6071 | // If we just saw a pack expansion into a non-pack, then directly convert |
6072 | // the remaining arguments, because we don't know what parameters they'll |
6073 | // match up with. |
6074 | if (PackExpansionIntoNonPack) { |
6075 | if (!SugaredArgumentPack.empty()) { |
6076 | // If we were part way through filling in an expanded parameter pack, |
6077 | // fall back to just producing individual arguments. |
6078 | SugaredConverted.insert(I: SugaredConverted.end(), |
6079 | From: SugaredArgumentPack.begin(), |
6080 | To: SugaredArgumentPack.end()); |
6081 | SugaredArgumentPack.clear(); |
6082 | |
6083 | CanonicalConverted.insert(I: CanonicalConverted.end(), |
6084 | From: CanonicalArgumentPack.begin(), |
6085 | To: CanonicalArgumentPack.end()); |
6086 | CanonicalArgumentPack.clear(); |
6087 | } |
6088 | |
6089 | while (ArgIdx < NumArgs) { |
6090 | const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument(); |
6091 | SugaredConverted.push_back(Elt: Arg); |
6092 | CanonicalConverted.push_back( |
6093 | Elt: Context.getCanonicalTemplateArgument(Arg)); |
6094 | ++ArgIdx; |
6095 | } |
6096 | |
6097 | return false; |
6098 | } |
6099 | |
6100 | continue; |
6101 | } |
6102 | |
6103 | // If we're checking a partial template argument list, we're done. |
6104 | if (PartialTemplateArgs) { |
6105 | if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) { |
6106 | SugaredConverted.push_back( |
6107 | Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack)); |
6108 | CanonicalConverted.push_back( |
6109 | Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack)); |
6110 | } |
6111 | return false; |
6112 | } |
6113 | |
6114 | // If we have a template parameter pack with no more corresponding |
6115 | // arguments, just break out now and we'll fill in the argument pack below. |
6116 | if ((*Param)->isTemplateParameterPack()) { |
6117 | assert(!getExpandedPackSize(*Param) && |
6118 | "Should have dealt with this already" ); |
6119 | |
6120 | // A non-expanded parameter pack before the end of the parameter list |
6121 | // only occurs for an ill-formed template parameter list, unless we've |
6122 | // got a partial argument list for a function template, so just bail out. |
6123 | if (Param + 1 != ParamEnd) { |
6124 | assert( |
6125 | (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) && |
6126 | "Concept templates must have parameter packs at the end." ); |
6127 | return true; |
6128 | } |
6129 | |
6130 | SugaredConverted.push_back( |
6131 | Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack)); |
6132 | SugaredArgumentPack.clear(); |
6133 | |
6134 | CanonicalConverted.push_back( |
6135 | Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack)); |
6136 | CanonicalArgumentPack.clear(); |
6137 | |
6138 | ++Param; |
6139 | continue; |
6140 | } |
6141 | |
6142 | // Check whether we have a default argument. |
6143 | TemplateArgumentLoc Arg; |
6144 | |
6145 | // Retrieve the default template argument from the template |
6146 | // parameter. For each kind of template parameter, we substitute the |
6147 | // template arguments provided thus far and any "outer" template arguments |
6148 | // (when the template parameter was part of a nested template) into |
6149 | // the default argument. |
6150 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param)) { |
6151 | if (!hasReachableDefaultArgument(TTP)) |
6152 | return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP, |
6153 | Args&: NewArgs); |
6154 | |
6155 | TypeSourceInfo *ArgType = SubstDefaultTemplateArgument( |
6156 | SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TTP, SugaredConverted, |
6157 | CanonicalConverted); |
6158 | if (!ArgType) |
6159 | return true; |
6160 | |
6161 | Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), |
6162 | ArgType); |
6163 | } else if (NonTypeTemplateParmDecl *NTTP |
6164 | = dyn_cast<NonTypeTemplateParmDecl>(Val: *Param)) { |
6165 | if (!hasReachableDefaultArgument(NTTP)) |
6166 | return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP, |
6167 | Args&: NewArgs); |
6168 | |
6169 | ExprResult E = SubstDefaultTemplateArgument( |
6170 | SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: NTTP, SugaredConverted, |
6171 | CanonicalConverted); |
6172 | if (E.isInvalid()) |
6173 | return true; |
6174 | |
6175 | Expr *Ex = E.getAs<Expr>(); |
6176 | Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); |
6177 | } else { |
6178 | TemplateTemplateParmDecl *TempParm |
6179 | = cast<TemplateTemplateParmDecl>(Val: *Param); |
6180 | |
6181 | if (!hasReachableDefaultArgument(TempParm)) |
6182 | return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TempParm, |
6183 | Args&: NewArgs); |
6184 | |
6185 | NestedNameSpecifierLoc QualifierLoc; |
6186 | TemplateName Name = SubstDefaultTemplateArgument( |
6187 | SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TempParm, SugaredConverted, |
6188 | CanonicalConverted, QualifierLoc); |
6189 | if (Name.isNull()) |
6190 | return true; |
6191 | |
6192 | Arg = TemplateArgumentLoc( |
6193 | Context, TemplateArgument(Name), QualifierLoc, |
6194 | TempParm->getDefaultArgument().getTemplateNameLoc()); |
6195 | } |
6196 | |
6197 | // Introduce an instantiation record that describes where we are using |
6198 | // the default template argument. We're not actually instantiating a |
6199 | // template here, we just create this object to put a note into the |
6200 | // context stack. |
6201 | InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, |
6202 | SugaredConverted, |
6203 | SourceRange(TemplateLoc, RAngleLoc)); |
6204 | if (Inst.isInvalid()) |
6205 | return true; |
6206 | |
6207 | // Check the default template argument. |
6208 | if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0, |
6209 | SugaredConverted, CanonicalConverted, |
6210 | CTAK_Specified)) |
6211 | return true; |
6212 | |
6213 | CanonicalConverted.back().setIsDefaulted(true); |
6214 | |
6215 | // Core issue 150 (assumed resolution): if this is a template template |
6216 | // parameter, keep track of the default template arguments from the |
6217 | // template definition. |
6218 | if (isTemplateTemplateParameter) |
6219 | NewArgs.addArgument(Loc: Arg); |
6220 | |
6221 | // Move to the next template parameter and argument. |
6222 | ++Param; |
6223 | ++ArgIdx; |
6224 | } |
6225 | |
6226 | // If we're performing a partial argument substitution, allow any trailing |
6227 | // pack expansions; they might be empty. This can happen even if |
6228 | // PartialTemplateArgs is false (the list of arguments is complete but |
6229 | // still dependent). |
6230 | if (ArgIdx < NumArgs && CurrentInstantiationScope && |
6231 | CurrentInstantiationScope->getPartiallySubstitutedPack()) { |
6232 | while (ArgIdx < NumArgs && |
6233 | NewArgs[ArgIdx].getArgument().isPackExpansion()) { |
6234 | const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument(); |
6235 | SugaredConverted.push_back(Elt: Arg); |
6236 | CanonicalConverted.push_back(Elt: Context.getCanonicalTemplateArgument(Arg)); |
6237 | } |
6238 | } |
6239 | |
6240 | // If we have any leftover arguments, then there were too many arguments. |
6241 | // Complain and fail. |
6242 | if (ArgIdx < NumArgs) { |
6243 | Diag(TemplateLoc, diag::err_template_arg_list_different_arity) |
6244 | << /*too many args*/1 |
6245 | << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) |
6246 | << Template |
6247 | << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc()); |
6248 | NoteTemplateLocation(*Template, Params->getSourceRange()); |
6249 | return true; |
6250 | } |
6251 | |
6252 | // No problems found with the new argument list, propagate changes back |
6253 | // to caller. |
6254 | if (UpdateArgsWithConversions) |
6255 | TemplateArgs = std::move(NewArgs); |
6256 | |
6257 | if (!PartialTemplateArgs) { |
6258 | // Setup the context/ThisScope for the case where we are needing to |
6259 | // re-instantiate constraints outside of normal instantiation. |
6260 | DeclContext *NewContext = Template->getDeclContext(); |
6261 | |
6262 | // If this template is in a template, make sure we extract the templated |
6263 | // decl. |
6264 | if (auto *TD = dyn_cast<TemplateDecl>(NewContext)) |
6265 | NewContext = Decl::castToDeclContext(TD->getTemplatedDecl()); |
6266 | auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext); |
6267 | |
6268 | Qualifiers ThisQuals; |
6269 | if (const auto *Method = |
6270 | dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl())) |
6271 | ThisQuals = Method->getMethodQualifiers(); |
6272 | |
6273 | ContextRAII Context(*this, NewContext); |
6274 | CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr); |
6275 | |
6276 | MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs( |
6277 | Template, NewContext, /*Final=*/false, CanonicalConverted, |
6278 | /*RelativeToPrimary=*/true, |
6279 | /*Pattern=*/nullptr, |
6280 | /*ForConceptInstantiation=*/true); |
6281 | if (EnsureTemplateArgumentListConstraints( |
6282 | Template, TemplateArgs: MLTAL, |
6283 | TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) { |
6284 | if (ConstraintsNotSatisfied) |
6285 | *ConstraintsNotSatisfied = true; |
6286 | return true; |
6287 | } |
6288 | } |
6289 | |
6290 | return false; |
6291 | } |
6292 | |
6293 | namespace { |
6294 | class UnnamedLocalNoLinkageFinder |
6295 | : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> |
6296 | { |
6297 | Sema &S; |
6298 | SourceRange SR; |
6299 | |
6300 | typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; |
6301 | |
6302 | public: |
6303 | UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } |
6304 | |
6305 | bool Visit(QualType T) { |
6306 | return T.isNull() ? false : inherited::Visit(T: T.getTypePtr()); |
6307 | } |
6308 | |
6309 | #define TYPE(Class, Parent) \ |
6310 | bool Visit##Class##Type(const Class##Type *); |
6311 | #define ABSTRACT_TYPE(Class, Parent) \ |
6312 | bool Visit##Class##Type(const Class##Type *) { return false; } |
6313 | #define NON_CANONICAL_TYPE(Class, Parent) \ |
6314 | bool Visit##Class##Type(const Class##Type *) { return false; } |
6315 | #include "clang/AST/TypeNodes.inc" |
6316 | |
6317 | bool VisitTagDecl(const TagDecl *Tag); |
6318 | bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); |
6319 | }; |
6320 | } // end anonymous namespace |
6321 | |
6322 | bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { |
6323 | return false; |
6324 | } |
6325 | |
6326 | bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { |
6327 | return Visit(T: T->getElementType()); |
6328 | } |
6329 | |
6330 | bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { |
6331 | return Visit(T: T->getPointeeType()); |
6332 | } |
6333 | |
6334 | bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( |
6335 | const BlockPointerType* T) { |
6336 | return Visit(T: T->getPointeeType()); |
6337 | } |
6338 | |
6339 | bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( |
6340 | const LValueReferenceType* T) { |
6341 | return Visit(T: T->getPointeeType()); |
6342 | } |
6343 | |
6344 | bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( |
6345 | const RValueReferenceType* T) { |
6346 | return Visit(T: T->getPointeeType()); |
6347 | } |
6348 | |
6349 | bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( |
6350 | const MemberPointerType* T) { |
6351 | return Visit(T: T->getPointeeType()) || Visit(T: QualType(T->getClass(), 0)); |
6352 | } |
6353 | |
6354 | bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( |
6355 | const ConstantArrayType* T) { |
6356 | return Visit(T: T->getElementType()); |
6357 | } |
6358 | |
6359 | bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( |
6360 | const IncompleteArrayType* T) { |
6361 | return Visit(T: T->getElementType()); |
6362 | } |
6363 | |
6364 | bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( |
6365 | const VariableArrayType* T) { |
6366 | return Visit(T: T->getElementType()); |
6367 | } |
6368 | |
6369 | bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( |
6370 | const DependentSizedArrayType* T) { |
6371 | return Visit(T: T->getElementType()); |
6372 | } |
6373 | |
6374 | bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( |
6375 | const DependentSizedExtVectorType* T) { |
6376 | return Visit(T: T->getElementType()); |
6377 | } |
6378 | |
6379 | bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType( |
6380 | const DependentSizedMatrixType *T) { |
6381 | return Visit(T: T->getElementType()); |
6382 | } |
6383 | |
6384 | bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType( |
6385 | const DependentAddressSpaceType *T) { |
6386 | return Visit(T: T->getPointeeType()); |
6387 | } |
6388 | |
6389 | bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { |
6390 | return Visit(T: T->getElementType()); |
6391 | } |
6392 | |
6393 | bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType( |
6394 | const DependentVectorType *T) { |
6395 | return Visit(T: T->getElementType()); |
6396 | } |
6397 | |
6398 | bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { |
6399 | return Visit(T: T->getElementType()); |
6400 | } |
6401 | |
6402 | bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType( |
6403 | const ConstantMatrixType *T) { |
6404 | return Visit(T: T->getElementType()); |
6405 | } |
6406 | |
6407 | bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( |
6408 | const FunctionProtoType* T) { |
6409 | for (const auto &A : T->param_types()) { |
6410 | if (Visit(T: A)) |
6411 | return true; |
6412 | } |
6413 | |
6414 | return Visit(T: T->getReturnType()); |
6415 | } |
6416 | |
6417 | bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( |
6418 | const FunctionNoProtoType* T) { |
6419 | return Visit(T: T->getReturnType()); |
6420 | } |
6421 | |
6422 | bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( |
6423 | const UnresolvedUsingType*) { |
6424 | return false; |
6425 | } |
6426 | |
6427 | bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { |
6428 | return false; |
6429 | } |
6430 | |
6431 | bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { |
6432 | return Visit(T: T->getUnmodifiedType()); |
6433 | } |
6434 | |
6435 | bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { |
6436 | return false; |
6437 | } |
6438 | |
6439 | bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType( |
6440 | const PackIndexingType *) { |
6441 | return false; |
6442 | } |
6443 | |
6444 | bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( |
6445 | const UnaryTransformType*) { |
6446 | return false; |
6447 | } |
6448 | |
6449 | bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { |
6450 | return Visit(T: T->getDeducedType()); |
6451 | } |
6452 | |
6453 | bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType( |
6454 | const DeducedTemplateSpecializationType *T) { |
6455 | return Visit(T: T->getDeducedType()); |
6456 | } |
6457 | |
6458 | bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { |
6459 | return VisitTagDecl(T->getDecl()); |
6460 | } |
6461 | |
6462 | bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { |
6463 | return VisitTagDecl(T->getDecl()); |
6464 | } |
6465 | |
6466 | bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( |
6467 | const TemplateTypeParmType*) { |
6468 | return false; |
6469 | } |
6470 | |
6471 | bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( |
6472 | const SubstTemplateTypeParmPackType *) { |
6473 | return false; |
6474 | } |
6475 | |
6476 | bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( |
6477 | const TemplateSpecializationType*) { |
6478 | return false; |
6479 | } |
6480 | |
6481 | bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( |
6482 | const InjectedClassNameType* T) { |
6483 | return VisitTagDecl(T->getDecl()); |
6484 | } |
6485 | |
6486 | bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( |
6487 | const DependentNameType* T) { |
6488 | return VisitNestedNameSpecifier(NNS: T->getQualifier()); |
6489 | } |
6490 | |
6491 | bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( |
6492 | const DependentTemplateSpecializationType* T) { |
6493 | if (auto *Q = T->getQualifier()) |
6494 | return VisitNestedNameSpecifier(NNS: Q); |
6495 | return false; |
6496 | } |
6497 | |
6498 | bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( |
6499 | const PackExpansionType* T) { |
6500 | return Visit(T: T->getPattern()); |
6501 | } |
6502 | |
6503 | bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { |
6504 | return false; |
6505 | } |
6506 | |
6507 | bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( |
6508 | const ObjCInterfaceType *) { |
6509 | return false; |
6510 | } |
6511 | |
6512 | bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( |
6513 | const ObjCObjectPointerType *) { |
6514 | return false; |
6515 | } |
6516 | |
6517 | bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) { |
6518 | return Visit(T: T->getValueType()); |
6519 | } |
6520 | |
6521 | bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) { |
6522 | return false; |
6523 | } |
6524 | |
6525 | bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) { |
6526 | return false; |
6527 | } |
6528 | |
6529 | bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType( |
6530 | const DependentBitIntType *T) { |
6531 | return false; |
6532 | } |
6533 | |
6534 | bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { |
6535 | if (Tag->getDeclContext()->isFunctionOrMethod()) { |
6536 | S.Diag(SR.getBegin(), |
6537 | S.getLangOpts().CPlusPlus11 ? |
6538 | diag::warn_cxx98_compat_template_arg_local_type : |
6539 | diag::ext_template_arg_local_type) |
6540 | << S.Context.getTypeDeclType(Tag) << SR; |
6541 | return true; |
6542 | } |
6543 | |
6544 | if (!Tag->hasNameForLinkage()) { |
6545 | S.Diag(SR.getBegin(), |
6546 | S.getLangOpts().CPlusPlus11 ? |
6547 | diag::warn_cxx98_compat_template_arg_unnamed_type : |
6548 | diag::ext_template_arg_unnamed_type) << SR; |
6549 | S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); |
6550 | return true; |
6551 | } |
6552 | |
6553 | return false; |
6554 | } |
6555 | |
6556 | bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( |
6557 | NestedNameSpecifier *NNS) { |
6558 | assert(NNS); |
6559 | if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS: NNS->getPrefix())) |
6560 | return true; |
6561 | |
6562 | switch (NNS->getKind()) { |
6563 | case NestedNameSpecifier::Identifier: |
6564 | case NestedNameSpecifier::Namespace: |
6565 | case NestedNameSpecifier::NamespaceAlias: |
6566 | case NestedNameSpecifier::Global: |
6567 | case NestedNameSpecifier::Super: |
6568 | return false; |
6569 | |
6570 | case NestedNameSpecifier::TypeSpec: |
6571 | case NestedNameSpecifier::TypeSpecWithTemplate: |
6572 | return Visit(T: QualType(NNS->getAsType(), 0)); |
6573 | } |
6574 | llvm_unreachable("Invalid NestedNameSpecifier::Kind!" ); |
6575 | } |
6576 | |
6577 | /// Check a template argument against its corresponding |
6578 | /// template type parameter. |
6579 | /// |
6580 | /// This routine implements the semantics of C++ [temp.arg.type]. It |
6581 | /// returns true if an error occurred, and false otherwise. |
6582 | bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) { |
6583 | assert(ArgInfo && "invalid TypeSourceInfo" ); |
6584 | QualType Arg = ArgInfo->getType(); |
6585 | SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); |
6586 | QualType CanonArg = Context.getCanonicalType(T: Arg); |
6587 | |
6588 | if (CanonArg->isVariablyModifiedType()) { |
6589 | return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; |
6590 | } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) { |
6591 | return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; |
6592 | } |
6593 | |
6594 | // C++03 [temp.arg.type]p2: |
6595 | // A local type, a type with no linkage, an unnamed type or a type |
6596 | // compounded from any of these types shall not be used as a |
6597 | // template-argument for a template type-parameter. |
6598 | // |
6599 | // C++11 allows these, and even in C++03 we allow them as an extension with |
6600 | // a warning. |
6601 | if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) { |
6602 | UnnamedLocalNoLinkageFinder Finder(*this, SR); |
6603 | (void)Finder.Visit(T: CanonArg); |
6604 | } |
6605 | |
6606 | return false; |
6607 | } |
6608 | |
6609 | enum NullPointerValueKind { |
6610 | NPV_NotNullPointer, |
6611 | NPV_NullPointer, |
6612 | NPV_Error |
6613 | }; |
6614 | |
6615 | /// Determine whether the given template argument is a null pointer |
6616 | /// value of the appropriate type. |
6617 | static NullPointerValueKind |
6618 | isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, |
6619 | QualType ParamType, Expr *Arg, |
6620 | Decl *Entity = nullptr) { |
6621 | if (Arg->isValueDependent() || Arg->isTypeDependent()) |
6622 | return NPV_NotNullPointer; |
6623 | |
6624 | // dllimport'd entities aren't constant but are available inside of template |
6625 | // arguments. |
6626 | if (Entity && Entity->hasAttr<DLLImportAttr>()) |
6627 | return NPV_NotNullPointer; |
6628 | |
6629 | if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType)) |
6630 | llvm_unreachable( |
6631 | "Incomplete parameter type in isNullPointerValueTemplateArgument!" ); |
6632 | |
6633 | if (!S.getLangOpts().CPlusPlus11) |
6634 | return NPV_NotNullPointer; |
6635 | |
6636 | // Determine whether we have a constant expression. |
6637 | ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg); |
6638 | if (ArgRV.isInvalid()) |
6639 | return NPV_Error; |
6640 | Arg = ArgRV.get(); |
6641 | |
6642 | Expr::EvalResult EvalResult; |
6643 | SmallVector<PartialDiagnosticAt, 8> Notes; |
6644 | EvalResult.Diag = &Notes; |
6645 | if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) || |
6646 | EvalResult.HasSideEffects) { |
6647 | SourceLocation DiagLoc = Arg->getExprLoc(); |
6648 | |
6649 | // If our only note is the usual "invalid subexpression" note, just point |
6650 | // the caret at its location rather than producing an essentially |
6651 | // redundant note. |
6652 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
6653 | diag::note_invalid_subexpr_in_const_expr) { |
6654 | DiagLoc = Notes[0].first; |
6655 | Notes.clear(); |
6656 | } |
6657 | |
6658 | S.Diag(DiagLoc, diag::err_template_arg_not_address_constant) |
6659 | << Arg->getType() << Arg->getSourceRange(); |
6660 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) |
6661 | S.Diag(Loc: Notes[I].first, PD: Notes[I].second); |
6662 | |
6663 | S.NoteTemplateParameterLocation(*Param); |
6664 | return NPV_Error; |
6665 | } |
6666 | |
6667 | // C++11 [temp.arg.nontype]p1: |
6668 | // - an address constant expression of type std::nullptr_t |
6669 | if (Arg->getType()->isNullPtrType()) |
6670 | return NPV_NullPointer; |
6671 | |
6672 | // - a constant expression that evaluates to a null pointer value (4.10); or |
6673 | // - a constant expression that evaluates to a null member pointer value |
6674 | // (4.11); or |
6675 | if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) || |
6676 | (EvalResult.Val.isMemberPointer() && |
6677 | !EvalResult.Val.getMemberPointerDecl())) { |
6678 | // If our expression has an appropriate type, we've succeeded. |
6679 | bool ObjCLifetimeConversion; |
6680 | if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) || |
6681 | S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false, |
6682 | ObjCLifetimeConversion)) |
6683 | return NPV_NullPointer; |
6684 | |
6685 | // The types didn't match, but we know we got a null pointer; complain, |
6686 | // then recover as if the types were correct. |
6687 | S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant) |
6688 | << Arg->getType() << ParamType << Arg->getSourceRange(); |
6689 | S.NoteTemplateParameterLocation(*Param); |
6690 | return NPV_NullPointer; |
6691 | } |
6692 | |
6693 | if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) { |
6694 | // We found a pointer that isn't null, but doesn't refer to an object. |
6695 | // We could just return NPV_NotNullPointer, but we can print a better |
6696 | // message with the information we have here. |
6697 | S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid) |
6698 | << EvalResult.Val.getAsString(S.Context, ParamType); |
6699 | S.NoteTemplateParameterLocation(*Param); |
6700 | return NPV_Error; |
6701 | } |
6702 | |
6703 | // If we don't have a null pointer value, but we do have a NULL pointer |
6704 | // constant, suggest a cast to the appropriate type. |
6705 | if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) { |
6706 | std::string Code = "static_cast<" + ParamType.getAsString() + ">(" ; |
6707 | S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant) |
6708 | << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code) |
6709 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()), |
6710 | ")" ); |
6711 | S.NoteTemplateParameterLocation(*Param); |
6712 | return NPV_NullPointer; |
6713 | } |
6714 | |
6715 | // FIXME: If we ever want to support general, address-constant expressions |
6716 | // as non-type template arguments, we should return the ExprResult here to |
6717 | // be interpreted by the caller. |
6718 | return NPV_NotNullPointer; |
6719 | } |
6720 | |
6721 | /// Checks whether the given template argument is compatible with its |
6722 | /// template parameter. |
6723 | static bool CheckTemplateArgumentIsCompatibleWithParameter( |
6724 | Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, |
6725 | Expr *Arg, QualType ArgType) { |
6726 | bool ObjCLifetimeConversion; |
6727 | if (ParamType->isPointerType() && |
6728 | !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() && |
6729 | S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false, |
6730 | ObjCLifetimeConversion)) { |
6731 | // For pointer-to-object types, qualification conversions are |
6732 | // permitted. |
6733 | } else { |
6734 | if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { |
6735 | if (!ParamRef->getPointeeType()->isFunctionType()) { |
6736 | // C++ [temp.arg.nontype]p5b3: |
6737 | // For a non-type template-parameter of type reference to |
6738 | // object, no conversions apply. The type referred to by the |
6739 | // reference may be more cv-qualified than the (otherwise |
6740 | // identical) type of the template- argument. The |
6741 | // template-parameter is bound directly to the |
6742 | // template-argument, which shall be an lvalue. |
6743 | |
6744 | // FIXME: Other qualifiers? |
6745 | unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); |
6746 | unsigned ArgQuals = ArgType.getCVRQualifiers(); |
6747 | |
6748 | if ((ParamQuals | ArgQuals) != ParamQuals) { |
6749 | S.Diag(Arg->getBeginLoc(), |
6750 | diag::err_template_arg_ref_bind_ignores_quals) |
6751 | << ParamType << Arg->getType() << Arg->getSourceRange(); |
6752 | S.NoteTemplateParameterLocation(*Param); |
6753 | return true; |
6754 | } |
6755 | } |
6756 | } |
6757 | |
6758 | // At this point, the template argument refers to an object or |
6759 | // function with external linkage. We now need to check whether the |
6760 | // argument and parameter types are compatible. |
6761 | if (!S.Context.hasSameUnqualifiedType(T1: ArgType, |
6762 | T2: ParamType.getNonReferenceType())) { |
6763 | // We can't perform this conversion or binding. |
6764 | if (ParamType->isReferenceType()) |
6765 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind) |
6766 | << ParamType << ArgIn->getType() << Arg->getSourceRange(); |
6767 | else |
6768 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) |
6769 | << ArgIn->getType() << ParamType << Arg->getSourceRange(); |
6770 | S.NoteTemplateParameterLocation(*Param); |
6771 | return true; |
6772 | } |
6773 | } |
6774 | |
6775 | return false; |
6776 | } |
6777 | |
6778 | /// Checks whether the given template argument is the address |
6779 | /// of an object or function according to C++ [temp.arg.nontype]p1. |
6780 | static bool CheckTemplateArgumentAddressOfObjectOrFunction( |
6781 | Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, |
6782 | TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) { |
6783 | bool Invalid = false; |
6784 | Expr *Arg = ArgIn; |
6785 | QualType ArgType = Arg->getType(); |
6786 | |
6787 | bool AddressTaken = false; |
6788 | SourceLocation AddrOpLoc; |
6789 | if (S.getLangOpts().MicrosoftExt) { |
6790 | // Microsoft Visual C++ strips all casts, allows an arbitrary number of |
6791 | // dereference and address-of operators. |
6792 | Arg = Arg->IgnoreParenCasts(); |
6793 | |
6794 | bool ExtWarnMSTemplateArg = false; |
6795 | UnaryOperatorKind FirstOpKind; |
6796 | SourceLocation FirstOpLoc; |
6797 | while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) { |
6798 | UnaryOperatorKind UnOpKind = UnOp->getOpcode(); |
6799 | if (UnOpKind == UO_Deref) |
6800 | ExtWarnMSTemplateArg = true; |
6801 | if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) { |
6802 | Arg = UnOp->getSubExpr()->IgnoreParenCasts(); |
6803 | if (!AddrOpLoc.isValid()) { |
6804 | FirstOpKind = UnOpKind; |
6805 | FirstOpLoc = UnOp->getOperatorLoc(); |
6806 | } |
6807 | } else |
6808 | break; |
6809 | } |
6810 | if (FirstOpLoc.isValid()) { |
6811 | if (ExtWarnMSTemplateArg) |
6812 | S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument) |
6813 | << ArgIn->getSourceRange(); |
6814 | |
6815 | if (FirstOpKind == UO_AddrOf) |
6816 | AddressTaken = true; |
6817 | else if (Arg->getType()->isPointerType()) { |
6818 | // We cannot let pointers get dereferenced here, that is obviously not a |
6819 | // constant expression. |
6820 | assert(FirstOpKind == UO_Deref); |
6821 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) |
6822 | << Arg->getSourceRange(); |
6823 | } |
6824 | } |
6825 | } else { |
6826 | // See through any implicit casts we added to fix the type. |
6827 | Arg = Arg->IgnoreImpCasts(); |
6828 | |
6829 | // C++ [temp.arg.nontype]p1: |
6830 | // |
6831 | // A template-argument for a non-type, non-template |
6832 | // template-parameter shall be one of: [...] |
6833 | // |
6834 | // -- the address of an object or function with external |
6835 | // linkage, including function templates and function |
6836 | // template-ids but excluding non-static class members, |
6837 | // expressed as & id-expression where the & is optional if |
6838 | // the name refers to a function or array, or if the |
6839 | // corresponding template-parameter is a reference; or |
6840 | |
6841 | // In C++98/03 mode, give an extension warning on any extra parentheses. |
6842 | // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 |
6843 | bool = false; |
6844 | while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) { |
6845 | if (!Invalid && !ExtraParens) { |
6846 | S.Diag(Arg->getBeginLoc(), |
6847 | S.getLangOpts().CPlusPlus11 |
6848 | ? diag::warn_cxx98_compat_template_arg_extra_parens |
6849 | : diag::ext_template_arg_extra_parens) |
6850 | << Arg->getSourceRange(); |
6851 | ExtraParens = true; |
6852 | } |
6853 | |
6854 | Arg = Parens->getSubExpr(); |
6855 | } |
6856 | |
6857 | while (SubstNonTypeTemplateParmExpr *subst = |
6858 | dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg)) |
6859 | Arg = subst->getReplacement()->IgnoreImpCasts(); |
6860 | |
6861 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) { |
6862 | if (UnOp->getOpcode() == UO_AddrOf) { |
6863 | Arg = UnOp->getSubExpr(); |
6864 | AddressTaken = true; |
6865 | AddrOpLoc = UnOp->getOperatorLoc(); |
6866 | } |
6867 | } |
6868 | |
6869 | while (SubstNonTypeTemplateParmExpr *subst = |
6870 | dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg)) |
6871 | Arg = subst->getReplacement()->IgnoreImpCasts(); |
6872 | } |
6873 | |
6874 | ValueDecl *Entity = nullptr; |
6875 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg)) |
6876 | Entity = DRE->getDecl(); |
6877 | else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg)) |
6878 | Entity = CUE->getGuidDecl(); |
6879 | |
6880 | // If our parameter has pointer type, check for a null template value. |
6881 | if (ParamType->isPointerType() || ParamType->isNullPtrType()) { |
6882 | switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn, |
6883 | Entity)) { |
6884 | case NPV_NullPointer: |
6885 | S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); |
6886 | SugaredConverted = TemplateArgument(ParamType, |
6887 | /*isNullPtr=*/true); |
6888 | CanonicalConverted = |
6889 | TemplateArgument(S.Context.getCanonicalType(T: ParamType), |
6890 | /*isNullPtr=*/true); |
6891 | return false; |
6892 | |
6893 | case NPV_Error: |
6894 | return true; |
6895 | |
6896 | case NPV_NotNullPointer: |
6897 | break; |
6898 | } |
6899 | } |
6900 | |
6901 | // Stop checking the precise nature of the argument if it is value dependent, |
6902 | // it should be checked when instantiated. |
6903 | if (Arg->isValueDependent()) { |
6904 | SugaredConverted = TemplateArgument(ArgIn); |
6905 | CanonicalConverted = |
6906 | S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
6907 | return false; |
6908 | } |
6909 | |
6910 | if (!Entity) { |
6911 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) |
6912 | << Arg->getSourceRange(); |
6913 | S.NoteTemplateParameterLocation(*Param); |
6914 | return true; |
6915 | } |
6916 | |
6917 | // Cannot refer to non-static data members |
6918 | if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) { |
6919 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field) |
6920 | << Entity << Arg->getSourceRange(); |
6921 | S.NoteTemplateParameterLocation(*Param); |
6922 | return true; |
6923 | } |
6924 | |
6925 | // Cannot refer to non-static member functions |
6926 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) { |
6927 | if (!Method->isStatic()) { |
6928 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method) |
6929 | << Method << Arg->getSourceRange(); |
6930 | S.NoteTemplateParameterLocation(*Param); |
6931 | return true; |
6932 | } |
6933 | } |
6934 | |
6935 | FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity); |
6936 | VarDecl *Var = dyn_cast<VarDecl>(Val: Entity); |
6937 | MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity); |
6938 | |
6939 | // A non-type template argument must refer to an object or function. |
6940 | if (!Func && !Var && !Guid) { |
6941 | // We found something, but we don't know specifically what it is. |
6942 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func) |
6943 | << Arg->getSourceRange(); |
6944 | S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here); |
6945 | return true; |
6946 | } |
6947 | |
6948 | // Address / reference template args must have external linkage in C++98. |
6949 | if (Entity->getFormalLinkage() == Linkage::Internal) { |
6950 | S.Diag(Arg->getBeginLoc(), |
6951 | S.getLangOpts().CPlusPlus11 |
6952 | ? diag::warn_cxx98_compat_template_arg_object_internal |
6953 | : diag::ext_template_arg_object_internal) |
6954 | << !Func << Entity << Arg->getSourceRange(); |
6955 | S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) |
6956 | << !Func; |
6957 | } else if (!Entity->hasLinkage()) { |
6958 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage) |
6959 | << !Func << Entity << Arg->getSourceRange(); |
6960 | S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) |
6961 | << !Func; |
6962 | return true; |
6963 | } |
6964 | |
6965 | if (Var) { |
6966 | // A value of reference type is not an object. |
6967 | if (Var->getType()->isReferenceType()) { |
6968 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var) |
6969 | << Var->getType() << Arg->getSourceRange(); |
6970 | S.NoteTemplateParameterLocation(*Param); |
6971 | return true; |
6972 | } |
6973 | |
6974 | // A template argument must have static storage duration. |
6975 | if (Var->getTLSKind()) { |
6976 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local) |
6977 | << Arg->getSourceRange(); |
6978 | S.Diag(Var->getLocation(), diag::note_template_arg_refers_here); |
6979 | return true; |
6980 | } |
6981 | } |
6982 | |
6983 | if (AddressTaken && ParamType->isReferenceType()) { |
6984 | // If we originally had an address-of operator, but the |
6985 | // parameter has reference type, complain and (if things look |
6986 | // like they will work) drop the address-of operator. |
6987 | if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(), |
6988 | T2: ParamType.getNonReferenceType())) { |
6989 | S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) |
6990 | << ParamType; |
6991 | S.NoteTemplateParameterLocation(*Param); |
6992 | return true; |
6993 | } |
6994 | |
6995 | S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) |
6996 | << ParamType |
6997 | << FixItHint::CreateRemoval(AddrOpLoc); |
6998 | S.NoteTemplateParameterLocation(*Param); |
6999 | |
7000 | ArgType = Entity->getType(); |
7001 | } |
7002 | |
7003 | // If the template parameter has pointer type, either we must have taken the |
7004 | // address or the argument must decay to a pointer. |
7005 | if (!AddressTaken && ParamType->isPointerType()) { |
7006 | if (Func) { |
7007 | // Function-to-pointer decay. |
7008 | ArgType = S.Context.getPointerType(Func->getType()); |
7009 | } else if (Entity->getType()->isArrayType()) { |
7010 | // Array-to-pointer decay. |
7011 | ArgType = S.Context.getArrayDecayedType(T: Entity->getType()); |
7012 | } else { |
7013 | // If the template parameter has pointer type but the address of |
7014 | // this object was not taken, complain and (possibly) recover by |
7015 | // taking the address of the entity. |
7016 | ArgType = S.Context.getPointerType(T: Entity->getType()); |
7017 | if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) { |
7018 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) |
7019 | << ParamType; |
7020 | S.NoteTemplateParameterLocation(*Param); |
7021 | return true; |
7022 | } |
7023 | |
7024 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) |
7025 | << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&" ); |
7026 | |
7027 | S.NoteTemplateParameterLocation(*Param); |
7028 | } |
7029 | } |
7030 | |
7031 | if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn, |
7032 | Arg, ArgType)) |
7033 | return true; |
7034 | |
7035 | // Create the template argument. |
7036 | SugaredConverted = TemplateArgument(Entity, ParamType); |
7037 | CanonicalConverted = |
7038 | TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), |
7039 | S.Context.getCanonicalType(T: ParamType)); |
7040 | S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false); |
7041 | return false; |
7042 | } |
7043 | |
7044 | /// Checks whether the given template argument is a pointer to |
7045 | /// member constant according to C++ [temp.arg.nontype]p1. |
7046 | static bool |
7047 | CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, |
7048 | QualType ParamType, Expr *&ResultArg, |
7049 | TemplateArgument &SugaredConverted, |
7050 | TemplateArgument &CanonicalConverted) { |
7051 | bool Invalid = false; |
7052 | |
7053 | Expr *Arg = ResultArg; |
7054 | bool ObjCLifetimeConversion; |
7055 | |
7056 | // C++ [temp.arg.nontype]p1: |
7057 | // |
7058 | // A template-argument for a non-type, non-template |
7059 | // template-parameter shall be one of: [...] |
7060 | // |
7061 | // -- a pointer to member expressed as described in 5.3.1. |
7062 | DeclRefExpr *DRE = nullptr; |
7063 | |
7064 | // In C++98/03 mode, give an extension warning on any extra parentheses. |
7065 | // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 |
7066 | bool = false; |
7067 | while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) { |
7068 | if (!Invalid && !ExtraParens) { |
7069 | S.Diag(Arg->getBeginLoc(), |
7070 | S.getLangOpts().CPlusPlus11 |
7071 | ? diag::warn_cxx98_compat_template_arg_extra_parens |
7072 | : diag::ext_template_arg_extra_parens) |
7073 | << Arg->getSourceRange(); |
7074 | ExtraParens = true; |
7075 | } |
7076 | |
7077 | Arg = Parens->getSubExpr(); |
7078 | } |
7079 | |
7080 | while (SubstNonTypeTemplateParmExpr *subst = |
7081 | dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg)) |
7082 | Arg = subst->getReplacement()->IgnoreImpCasts(); |
7083 | |
7084 | // A pointer-to-member constant written &Class::member. |
7085 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) { |
7086 | if (UnOp->getOpcode() == UO_AddrOf) { |
7087 | DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr()); |
7088 | if (DRE && !DRE->getQualifier()) |
7089 | DRE = nullptr; |
7090 | } |
7091 | } |
7092 | // A constant of pointer-to-member type. |
7093 | else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) { |
7094 | ValueDecl *VD = DRE->getDecl(); |
7095 | if (VD->getType()->isMemberPointerType()) { |
7096 | if (isa<NonTypeTemplateParmDecl>(Val: VD)) { |
7097 | if (Arg->isTypeDependent() || Arg->isValueDependent()) { |
7098 | SugaredConverted = TemplateArgument(Arg); |
7099 | CanonicalConverted = |
7100 | S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
7101 | } else { |
7102 | SugaredConverted = TemplateArgument(VD, ParamType); |
7103 | CanonicalConverted = |
7104 | TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), |
7105 | S.Context.getCanonicalType(T: ParamType)); |
7106 | } |
7107 | return Invalid; |
7108 | } |
7109 | } |
7110 | |
7111 | DRE = nullptr; |
7112 | } |
7113 | |
7114 | ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr; |
7115 | |
7116 | // Check for a null pointer value. |
7117 | switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg, |
7118 | Entity)) { |
7119 | case NPV_Error: |
7120 | return true; |
7121 | case NPV_NullPointer: |
7122 | S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); |
7123 | SugaredConverted = TemplateArgument(ParamType, |
7124 | /*isNullPtr*/ true); |
7125 | CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType), |
7126 | /*isNullPtr*/ true); |
7127 | return false; |
7128 | case NPV_NotNullPointer: |
7129 | break; |
7130 | } |
7131 | |
7132 | if (S.IsQualificationConversion(FromType: ResultArg->getType(), |
7133 | ToType: ParamType.getNonReferenceType(), CStyle: false, |
7134 | ObjCLifetimeConversion)) { |
7135 | ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp, |
7136 | VK: ResultArg->getValueKind()) |
7137 | .get(); |
7138 | } else if (!S.Context.hasSameUnqualifiedType( |
7139 | T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) { |
7140 | // We can't perform this conversion. |
7141 | S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible) |
7142 | << ResultArg->getType() << ParamType << ResultArg->getSourceRange(); |
7143 | S.NoteTemplateParameterLocation(*Param); |
7144 | return true; |
7145 | } |
7146 | |
7147 | if (!DRE) |
7148 | return S.Diag(Arg->getBeginLoc(), |
7149 | diag::err_template_arg_not_pointer_to_member_form) |
7150 | << Arg->getSourceRange(); |
7151 | |
7152 | if (isa<FieldDecl>(Val: DRE->getDecl()) || |
7153 | isa<IndirectFieldDecl>(Val: DRE->getDecl()) || |
7154 | isa<CXXMethodDecl>(Val: DRE->getDecl())) { |
7155 | assert((isa<FieldDecl>(DRE->getDecl()) || |
7156 | isa<IndirectFieldDecl>(DRE->getDecl()) || |
7157 | cast<CXXMethodDecl>(DRE->getDecl()) |
7158 | ->isImplicitObjectMemberFunction()) && |
7159 | "Only non-static member pointers can make it here" ); |
7160 | |
7161 | // Okay: this is the address of a non-static member, and therefore |
7162 | // a member pointer constant. |
7163 | if (Arg->isTypeDependent() || Arg->isValueDependent()) { |
7164 | SugaredConverted = TemplateArgument(Arg); |
7165 | CanonicalConverted = |
7166 | S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
7167 | } else { |
7168 | ValueDecl *D = DRE->getDecl(); |
7169 | SugaredConverted = TemplateArgument(D, ParamType); |
7170 | CanonicalConverted = |
7171 | TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()), |
7172 | S.Context.getCanonicalType(T: ParamType)); |
7173 | } |
7174 | return Invalid; |
7175 | } |
7176 | |
7177 | // We found something else, but we don't know specifically what it is. |
7178 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form) |
7179 | << Arg->getSourceRange(); |
7180 | S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); |
7181 | return true; |
7182 | } |
7183 | |
7184 | /// Check a template argument against its corresponding |
7185 | /// non-type template parameter. |
7186 | /// |
7187 | /// This routine implements the semantics of C++ [temp.arg.nontype]. |
7188 | /// If an error occurred, it returns ExprError(); otherwise, it |
7189 | /// returns the converted template argument. \p ParamType is the |
7190 | /// type of the non-type template parameter after it has been instantiated. |
7191 | ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, |
7192 | QualType ParamType, Expr *Arg, |
7193 | TemplateArgument &SugaredConverted, |
7194 | TemplateArgument &CanonicalConverted, |
7195 | CheckTemplateArgumentKind CTAK) { |
7196 | SourceLocation StartLoc = Arg->getBeginLoc(); |
7197 | |
7198 | // If the parameter type somehow involves auto, deduce the type now. |
7199 | DeducedType *DeducedT = ParamType->getContainedDeducedType(); |
7200 | if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) { |
7201 | // During template argument deduction, we allow 'decltype(auto)' to |
7202 | // match an arbitrary dependent argument. |
7203 | // FIXME: The language rules don't say what happens in this case. |
7204 | // FIXME: We get an opaque dependent type out of decltype(auto) if the |
7205 | // expression is merely instantiation-dependent; is this enough? |
7206 | if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) { |
7207 | auto *AT = dyn_cast<AutoType>(Val: DeducedT); |
7208 | if (AT && AT->isDecltypeAuto()) { |
7209 | SugaredConverted = TemplateArgument(Arg); |
7210 | CanonicalConverted = TemplateArgument( |
7211 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted)); |
7212 | return Arg; |
7213 | } |
7214 | } |
7215 | |
7216 | // When checking a deduced template argument, deduce from its type even if |
7217 | // the type is dependent, in order to check the types of non-type template |
7218 | // arguments line up properly in partial ordering. |
7219 | Expr *DeductionArg = Arg; |
7220 | if (auto *PE = dyn_cast<PackExpansionExpr>(Val: DeductionArg)) |
7221 | DeductionArg = PE->getPattern(); |
7222 | TypeSourceInfo *TSI = |
7223 | Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation()); |
7224 | if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) { |
7225 | InitializedEntity Entity = |
7226 | InitializedEntity::InitializeTemplateParameter(T: ParamType, Param); |
7227 | InitializationKind Kind = InitializationKind::CreateForInit( |
7228 | Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg); |
7229 | Expr *Inits[1] = {DeductionArg}; |
7230 | ParamType = |
7231 | DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits); |
7232 | if (ParamType.isNull()) |
7233 | return ExprError(); |
7234 | } else { |
7235 | TemplateDeductionInfo Info(DeductionArg->getExprLoc(), |
7236 | Param->getDepth() + 1); |
7237 | ParamType = QualType(); |
7238 | TemplateDeductionResult Result = |
7239 | DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info, |
7240 | /*DependentDeduction=*/true, |
7241 | // We do not check constraints right now because the |
7242 | // immediately-declared constraint of the auto type is |
7243 | // also an associated constraint, and will be checked |
7244 | // along with the other associated constraints after |
7245 | // checking the template argument list. |
7246 | /*IgnoreConstraints=*/true); |
7247 | if (Result == TemplateDeductionResult::AlreadyDiagnosed) { |
7248 | if (ParamType.isNull()) |
7249 | return ExprError(); |
7250 | } else if (Result != TemplateDeductionResult::Success) { |
7251 | Diag(Arg->getExprLoc(), |
7252 | diag::err_non_type_template_parm_type_deduction_failure) |
7253 | << Param->getDeclName() << Param->getType() << Arg->getType() |
7254 | << Arg->getSourceRange(); |
7255 | NoteTemplateParameterLocation(*Param); |
7256 | return ExprError(); |
7257 | } |
7258 | } |
7259 | // CheckNonTypeTemplateParameterType will produce a diagnostic if there's |
7260 | // an error. The error message normally references the parameter |
7261 | // declaration, but here we'll pass the argument location because that's |
7262 | // where the parameter type is deduced. |
7263 | ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc()); |
7264 | if (ParamType.isNull()) { |
7265 | NoteTemplateParameterLocation(*Param); |
7266 | return ExprError(); |
7267 | } |
7268 | } |
7269 | |
7270 | // We should have already dropped all cv-qualifiers by now. |
7271 | assert(!ParamType.hasQualifiers() && |
7272 | "non-type template parameter type cannot be qualified" ); |
7273 | |
7274 | // FIXME: When Param is a reference, should we check that Arg is an lvalue? |
7275 | if (CTAK == CTAK_Deduced && |
7276 | (ParamType->isReferenceType() |
7277 | ? !Context.hasSameType(T1: ParamType.getNonReferenceType(), |
7278 | T2: Arg->getType()) |
7279 | : !Context.hasSameUnqualifiedType(T1: ParamType, T2: Arg->getType()))) { |
7280 | // FIXME: If either type is dependent, we skip the check. This isn't |
7281 | // correct, since during deduction we're supposed to have replaced each |
7282 | // template parameter with some unique (non-dependent) placeholder. |
7283 | // FIXME: If the argument type contains 'auto', we carry on and fail the |
7284 | // type check in order to force specific types to be more specialized than |
7285 | // 'auto'. It's not clear how partial ordering with 'auto' is supposed to |
7286 | // work. Similarly for CTAD, when comparing 'A<x>' against 'A'. |
7287 | if ((ParamType->isDependentType() || Arg->isTypeDependent()) && |
7288 | !Arg->getType()->getContainedDeducedType()) { |
7289 | SugaredConverted = TemplateArgument(Arg); |
7290 | CanonicalConverted = TemplateArgument( |
7291 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted)); |
7292 | return Arg; |
7293 | } |
7294 | // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770, |
7295 | // we should actually be checking the type of the template argument in P, |
7296 | // not the type of the template argument deduced from A, against the |
7297 | // template parameter type. |
7298 | Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) |
7299 | << Arg->getType() |
7300 | << ParamType.getUnqualifiedType(); |
7301 | NoteTemplateParameterLocation(*Param); |
7302 | return ExprError(); |
7303 | } |
7304 | |
7305 | // If either the parameter has a dependent type or the argument is |
7306 | // type-dependent, there's nothing we can check now. |
7307 | if (ParamType->isDependentType() || Arg->isTypeDependent()) { |
7308 | // Force the argument to the type of the parameter to maintain invariants. |
7309 | auto *PE = dyn_cast<PackExpansionExpr>(Val: Arg); |
7310 | if (PE) |
7311 | Arg = PE->getPattern(); |
7312 | ExprResult E = ImpCastExprToType( |
7313 | E: Arg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent, |
7314 | VK: ParamType->isLValueReferenceType() ? VK_LValue |
7315 | : ParamType->isRValueReferenceType() ? VK_XValue |
7316 | : VK_PRValue); |
7317 | if (E.isInvalid()) |
7318 | return ExprError(); |
7319 | if (PE) { |
7320 | // Recreate a pack expansion if we unwrapped one. |
7321 | E = new (Context) |
7322 | PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(), |
7323 | PE->getNumExpansions()); |
7324 | } |
7325 | SugaredConverted = TemplateArgument(E.get()); |
7326 | CanonicalConverted = TemplateArgument( |
7327 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted)); |
7328 | return E; |
7329 | } |
7330 | |
7331 | QualType CanonParamType = Context.getCanonicalType(T: ParamType); |
7332 | // Avoid making a copy when initializing a template parameter of class type |
7333 | // from a template parameter object of the same type. This is going beyond |
7334 | // the standard, but is required for soundness: in |
7335 | // template<A a> struct X { X *p; X<a> *q; }; |
7336 | // ... we need p and q to have the same type. |
7337 | // |
7338 | // Similarly, don't inject a call to a copy constructor when initializing |
7339 | // from a template parameter of the same type. |
7340 | Expr *InnerArg = Arg->IgnoreParenImpCasts(); |
7341 | if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) && |
7342 | Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) { |
7343 | NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl(); |
7344 | if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { |
7345 | |
7346 | SugaredConverted = TemplateArgument(TPO, ParamType); |
7347 | CanonicalConverted = |
7348 | TemplateArgument(TPO->getCanonicalDecl(), CanonParamType); |
7349 | return Arg; |
7350 | } |
7351 | if (isa<NonTypeTemplateParmDecl>(Val: ND)) { |
7352 | SugaredConverted = TemplateArgument(Arg); |
7353 | CanonicalConverted = |
7354 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
7355 | return Arg; |
7356 | } |
7357 | } |
7358 | |
7359 | // The initialization of the parameter from the argument is |
7360 | // a constant-evaluated context. |
7361 | EnterExpressionEvaluationContext ConstantEvaluated( |
7362 | *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
7363 | |
7364 | bool IsConvertedConstantExpression = true; |
7365 | if (isa<InitListExpr>(Val: Arg) || ParamType->isRecordType()) { |
7366 | InitializationKind Kind = InitializationKind::CreateForInit( |
7367 | Loc: Arg->getBeginLoc(), /*DirectInit=*/false, Init: Arg); |
7368 | Expr *Inits[1] = {Arg}; |
7369 | InitializedEntity Entity = |
7370 | InitializedEntity::InitializeTemplateParameter(T: ParamType, Param); |
7371 | InitializationSequence InitSeq(*this, Entity, Kind, Inits); |
7372 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits); |
7373 | if (Result.isInvalid() || !Result.get()) |
7374 | return ExprError(); |
7375 | Result = ActOnConstantExpression(Res: Result.get()); |
7376 | if (Result.isInvalid() || !Result.get()) |
7377 | return ExprError(); |
7378 | Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(), |
7379 | /*DiscardedValue=*/false, |
7380 | /*IsConstexpr=*/true, /*IsTemplateArgument=*/true) |
7381 | .get(); |
7382 | IsConvertedConstantExpression = false; |
7383 | } |
7384 | |
7385 | if (getLangOpts().CPlusPlus17) { |
7386 | // C++17 [temp.arg.nontype]p1: |
7387 | // A template-argument for a non-type template parameter shall be |
7388 | // a converted constant expression of the type of the template-parameter. |
7389 | APValue Value; |
7390 | ExprResult ArgResult; |
7391 | if (IsConvertedConstantExpression) { |
7392 | ArgResult = BuildConvertedConstantExpression(Arg, ParamType, |
7393 | CCEK_TemplateArg, Param); |
7394 | if (ArgResult.isInvalid()) |
7395 | return ExprError(); |
7396 | } else { |
7397 | ArgResult = Arg; |
7398 | } |
7399 | |
7400 | // For a value-dependent argument, CheckConvertedConstantExpression is |
7401 | // permitted (and expected) to be unable to determine a value. |
7402 | if (ArgResult.get()->isValueDependent()) { |
7403 | SugaredConverted = TemplateArgument(ArgResult.get()); |
7404 | CanonicalConverted = |
7405 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
7406 | return ArgResult; |
7407 | } |
7408 | |
7409 | APValue PreNarrowingValue; |
7410 | ArgResult = EvaluateConvertedConstantExpression( |
7411 | E: ArgResult.get(), T: ParamType, Value, CCE: CCEK_TemplateArg, /*RequireInt=*/ |
7412 | false, PreNarrowingValue); |
7413 | if (ArgResult.isInvalid()) |
7414 | return ExprError(); |
7415 | |
7416 | if (Value.isLValue()) { |
7417 | APValue::LValueBase Base = Value.getLValueBase(); |
7418 | auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>()); |
7419 | // For a non-type template-parameter of pointer or reference type, |
7420 | // the value of the constant expression shall not refer to |
7421 | assert(ParamType->isPointerType() || ParamType->isReferenceType() || |
7422 | ParamType->isNullPtrType()); |
7423 | // -- a temporary object |
7424 | // -- a string literal |
7425 | // -- the result of a typeid expression, or |
7426 | // -- a predefined __func__ variable |
7427 | if (Base && |
7428 | (!VD || |
7429 | isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) { |
7430 | Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) |
7431 | << Arg->getSourceRange(); |
7432 | return ExprError(); |
7433 | } |
7434 | |
7435 | if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD && |
7436 | VD->getType()->isArrayType() && |
7437 | Value.getLValuePath()[0].getAsArrayIndex() == 0 && |
7438 | !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) { |
7439 | SugaredConverted = TemplateArgument(VD, ParamType); |
7440 | CanonicalConverted = TemplateArgument( |
7441 | cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType); |
7442 | return ArgResult.get(); |
7443 | } |
7444 | |
7445 | // -- a subobject [until C++20] |
7446 | if (!getLangOpts().CPlusPlus20) { |
7447 | if (!Value.hasLValuePath() || Value.getLValuePath().size() || |
7448 | Value.isLValueOnePastTheEnd()) { |
7449 | Diag(StartLoc, diag::err_non_type_template_arg_subobject) |
7450 | << Value.getAsString(Context, ParamType); |
7451 | return ExprError(); |
7452 | } |
7453 | assert((VD || !ParamType->isReferenceType()) && |
7454 | "null reference should not be a constant expression" ); |
7455 | assert((!VD || !ParamType->isNullPtrType()) && |
7456 | "non-null value of type nullptr_t?" ); |
7457 | } |
7458 | } |
7459 | |
7460 | if (Value.isAddrLabelDiff()) |
7461 | return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff); |
7462 | |
7463 | SugaredConverted = TemplateArgument(Context, ParamType, Value); |
7464 | CanonicalConverted = TemplateArgument(Context, CanonParamType, Value); |
7465 | return ArgResult.get(); |
7466 | } |
7467 | |
7468 | // C++ [temp.arg.nontype]p5: |
7469 | // The following conversions are performed on each expression used |
7470 | // as a non-type template-argument. If a non-type |
7471 | // template-argument cannot be converted to the type of the |
7472 | // corresponding template-parameter then the program is |
7473 | // ill-formed. |
7474 | if (ParamType->isIntegralOrEnumerationType()) { |
7475 | // C++11: |
7476 | // -- for a non-type template-parameter of integral or |
7477 | // enumeration type, conversions permitted in a converted |
7478 | // constant expression are applied. |
7479 | // |
7480 | // C++98: |
7481 | // -- for a non-type template-parameter of integral or |
7482 | // enumeration type, integral promotions (4.5) and integral |
7483 | // conversions (4.7) are applied. |
7484 | |
7485 | if (getLangOpts().CPlusPlus11) { |
7486 | // C++ [temp.arg.nontype]p1: |
7487 | // A template-argument for a non-type, non-template template-parameter |
7488 | // shall be one of: |
7489 | // |
7490 | // -- for a non-type template-parameter of integral or enumeration |
7491 | // type, a converted constant expression of the type of the |
7492 | // template-parameter; or |
7493 | llvm::APSInt Value; |
7494 | ExprResult ArgResult = |
7495 | CheckConvertedConstantExpression(From: Arg, T: ParamType, Value, |
7496 | CCE: CCEK_TemplateArg); |
7497 | if (ArgResult.isInvalid()) |
7498 | return ExprError(); |
7499 | |
7500 | // We can't check arbitrary value-dependent arguments. |
7501 | if (ArgResult.get()->isValueDependent()) { |
7502 | SugaredConverted = TemplateArgument(ArgResult.get()); |
7503 | CanonicalConverted = |
7504 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
7505 | return ArgResult; |
7506 | } |
7507 | |
7508 | // Widen the argument value to sizeof(parameter type). This is almost |
7509 | // always a no-op, except when the parameter type is bool. In |
7510 | // that case, this may extend the argument from 1 bit to 8 bits. |
7511 | QualType IntegerType = ParamType; |
7512 | if (const EnumType *Enum = IntegerType->getAs<EnumType>()) |
7513 | IntegerType = Enum->getDecl()->getIntegerType(); |
7514 | Value = Value.extOrTrunc(width: IntegerType->isBitIntType() |
7515 | ? Context.getIntWidth(T: IntegerType) |
7516 | : Context.getTypeSize(T: IntegerType)); |
7517 | |
7518 | SugaredConverted = TemplateArgument(Context, Value, ParamType); |
7519 | CanonicalConverted = |
7520 | TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType)); |
7521 | return ArgResult; |
7522 | } |
7523 | |
7524 | ExprResult ArgResult = DefaultLvalueConversion(E: Arg); |
7525 | if (ArgResult.isInvalid()) |
7526 | return ExprError(); |
7527 | Arg = ArgResult.get(); |
7528 | |
7529 | QualType ArgType = Arg->getType(); |
7530 | |
7531 | // C++ [temp.arg.nontype]p1: |
7532 | // A template-argument for a non-type, non-template |
7533 | // template-parameter shall be one of: |
7534 | // |
7535 | // -- an integral constant-expression of integral or enumeration |
7536 | // type; or |
7537 | // -- the name of a non-type template-parameter; or |
7538 | llvm::APSInt Value; |
7539 | if (!ArgType->isIntegralOrEnumerationType()) { |
7540 | Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral) |
7541 | << ArgType << Arg->getSourceRange(); |
7542 | NoteTemplateParameterLocation(*Param); |
7543 | return ExprError(); |
7544 | } else if (!Arg->isValueDependent()) { |
7545 | class TmplArgICEDiagnoser : public VerifyICEDiagnoser { |
7546 | QualType T; |
7547 | |
7548 | public: |
7549 | TmplArgICEDiagnoser(QualType T) : T(T) { } |
7550 | |
7551 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, |
7552 | SourceLocation Loc) override { |
7553 | return S.Diag(Loc, diag::err_template_arg_not_ice) << T; |
7554 | } |
7555 | } Diagnoser(ArgType); |
7556 | |
7557 | Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get(); |
7558 | if (!Arg) |
7559 | return ExprError(); |
7560 | } |
7561 | |
7562 | // From here on out, all we care about is the unqualified form |
7563 | // of the argument type. |
7564 | ArgType = ArgType.getUnqualifiedType(); |
7565 | |
7566 | // Try to convert the argument to the parameter's type. |
7567 | if (Context.hasSameType(T1: ParamType, T2: ArgType)) { |
7568 | // Okay: no conversion necessary |
7569 | } else if (ParamType->isBooleanType()) { |
7570 | // This is an integral-to-boolean conversion. |
7571 | Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get(); |
7572 | } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) || |
7573 | !ParamType->isEnumeralType()) { |
7574 | // This is an integral promotion or conversion. |
7575 | Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get(); |
7576 | } else { |
7577 | // We can't perform this conversion. |
7578 | Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) |
7579 | << Arg->getType() << ParamType << Arg->getSourceRange(); |
7580 | NoteTemplateParameterLocation(*Param); |
7581 | return ExprError(); |
7582 | } |
7583 | |
7584 | // Add the value of this argument to the list of converted |
7585 | // arguments. We use the bitwidth and signedness of the template |
7586 | // parameter. |
7587 | if (Arg->isValueDependent()) { |
7588 | // The argument is value-dependent. Create a new |
7589 | // TemplateArgument with the converted expression. |
7590 | SugaredConverted = TemplateArgument(Arg); |
7591 | CanonicalConverted = |
7592 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
7593 | return Arg; |
7594 | } |
7595 | |
7596 | QualType IntegerType = ParamType; |
7597 | if (const EnumType *Enum = IntegerType->getAs<EnumType>()) { |
7598 | IntegerType = Enum->getDecl()->getIntegerType(); |
7599 | } |
7600 | |
7601 | if (ParamType->isBooleanType()) { |
7602 | // Value must be zero or one. |
7603 | Value = Value != 0; |
7604 | unsigned AllowedBits = Context.getTypeSize(T: IntegerType); |
7605 | if (Value.getBitWidth() != AllowedBits) |
7606 | Value = Value.extOrTrunc(width: AllowedBits); |
7607 | Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); |
7608 | } else { |
7609 | llvm::APSInt OldValue = Value; |
7610 | |
7611 | // Coerce the template argument's value to the value it will have |
7612 | // based on the template parameter's type. |
7613 | unsigned AllowedBits = IntegerType->isBitIntType() |
7614 | ? Context.getIntWidth(T: IntegerType) |
7615 | : Context.getTypeSize(T: IntegerType); |
7616 | if (Value.getBitWidth() != AllowedBits) |
7617 | Value = Value.extOrTrunc(width: AllowedBits); |
7618 | Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); |
7619 | |
7620 | // Complain if an unsigned parameter received a negative value. |
7621 | if (IntegerType->isUnsignedIntegerOrEnumerationType() && |
7622 | (OldValue.isSigned() && OldValue.isNegative())) { |
7623 | Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative) |
7624 | << toString(OldValue, 10) << toString(Value, 10) << Param->getType() |
7625 | << Arg->getSourceRange(); |
7626 | NoteTemplateParameterLocation(*Param); |
7627 | } |
7628 | |
7629 | // Complain if we overflowed the template parameter's type. |
7630 | unsigned RequiredBits; |
7631 | if (IntegerType->isUnsignedIntegerOrEnumerationType()) |
7632 | RequiredBits = OldValue.getActiveBits(); |
7633 | else if (OldValue.isUnsigned()) |
7634 | RequiredBits = OldValue.getActiveBits() + 1; |
7635 | else |
7636 | RequiredBits = OldValue.getSignificantBits(); |
7637 | if (RequiredBits > AllowedBits) { |
7638 | Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large) |
7639 | << toString(OldValue, 10) << toString(Value, 10) << Param->getType() |
7640 | << Arg->getSourceRange(); |
7641 | NoteTemplateParameterLocation(*Param); |
7642 | } |
7643 | } |
7644 | |
7645 | QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType; |
7646 | SugaredConverted = TemplateArgument(Context, Value, T); |
7647 | CanonicalConverted = |
7648 | TemplateArgument(Context, Value, Context.getCanonicalType(T)); |
7649 | return Arg; |
7650 | } |
7651 | |
7652 | QualType ArgType = Arg->getType(); |
7653 | DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction |
7654 | |
7655 | // Handle pointer-to-function, reference-to-function, and |
7656 | // pointer-to-member-function all in (roughly) the same way. |
7657 | if (// -- For a non-type template-parameter of type pointer to |
7658 | // function, only the function-to-pointer conversion (4.3) is |
7659 | // applied. If the template-argument represents a set of |
7660 | // overloaded functions (or a pointer to such), the matching |
7661 | // function is selected from the set (13.4). |
7662 | (ParamType->isPointerType() && |
7663 | ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) || |
7664 | // -- For a non-type template-parameter of type reference to |
7665 | // function, no conversions apply. If the template-argument |
7666 | // represents a set of overloaded functions, the matching |
7667 | // function is selected from the set (13.4). |
7668 | (ParamType->isReferenceType() && |
7669 | ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) || |
7670 | // -- For a non-type template-parameter of type pointer to |
7671 | // member function, no conversions apply. If the |
7672 | // template-argument represents a set of overloaded member |
7673 | // functions, the matching member function is selected from |
7674 | // the set (13.4). |
7675 | (ParamType->isMemberPointerType() && |
7676 | ParamType->castAs<MemberPointerType>()->getPointeeType() |
7677 | ->isFunctionType())) { |
7678 | |
7679 | if (Arg->getType() == Context.OverloadTy) { |
7680 | if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType, |
7681 | Complain: true, |
7682 | Found&: FoundResult)) { |
7683 | if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc())) |
7684 | return ExprError(); |
7685 | |
7686 | ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn); |
7687 | if (Res.isInvalid()) |
7688 | return ExprError(); |
7689 | Arg = Res.get(); |
7690 | ArgType = Arg->getType(); |
7691 | } else |
7692 | return ExprError(); |
7693 | } |
7694 | |
7695 | if (!ParamType->isMemberPointerType()) { |
7696 | if (CheckTemplateArgumentAddressOfObjectOrFunction( |
7697 | S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, |
7698 | CanonicalConverted)) |
7699 | return ExprError(); |
7700 | return Arg; |
7701 | } |
7702 | |
7703 | if (CheckTemplateArgumentPointerToMember( |
7704 | S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted)) |
7705 | return ExprError(); |
7706 | return Arg; |
7707 | } |
7708 | |
7709 | if (ParamType->isPointerType()) { |
7710 | // -- for a non-type template-parameter of type pointer to |
7711 | // object, qualification conversions (4.4) and the |
7712 | // array-to-pointer conversion (4.2) are applied. |
7713 | // C++0x also allows a value of std::nullptr_t. |
7714 | assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && |
7715 | "Only object pointers allowed here" ); |
7716 | |
7717 | if (CheckTemplateArgumentAddressOfObjectOrFunction( |
7718 | S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted)) |
7719 | return ExprError(); |
7720 | return Arg; |
7721 | } |
7722 | |
7723 | if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { |
7724 | // -- For a non-type template-parameter of type reference to |
7725 | // object, no conversions apply. The type referred to by the |
7726 | // reference may be more cv-qualified than the (otherwise |
7727 | // identical) type of the template-argument. The |
7728 | // template-parameter is bound directly to the |
7729 | // template-argument, which must be an lvalue. |
7730 | assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && |
7731 | "Only object references allowed here" ); |
7732 | |
7733 | if (Arg->getType() == Context.OverloadTy) { |
7734 | if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, |
7735 | TargetType: ParamRefType->getPointeeType(), |
7736 | Complain: true, |
7737 | Found&: FoundResult)) { |
7738 | if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc())) |
7739 | return ExprError(); |
7740 | ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn); |
7741 | if (Res.isInvalid()) |
7742 | return ExprError(); |
7743 | Arg = Res.get(); |
7744 | ArgType = Arg->getType(); |
7745 | } else |
7746 | return ExprError(); |
7747 | } |
7748 | |
7749 | if (CheckTemplateArgumentAddressOfObjectOrFunction( |
7750 | S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted)) |
7751 | return ExprError(); |
7752 | return Arg; |
7753 | } |
7754 | |
7755 | // Deal with parameters of type std::nullptr_t. |
7756 | if (ParamType->isNullPtrType()) { |
7757 | if (Arg->isTypeDependent() || Arg->isValueDependent()) { |
7758 | SugaredConverted = TemplateArgument(Arg); |
7759 | CanonicalConverted = |
7760 | Context.getCanonicalTemplateArgument(Arg: SugaredConverted); |
7761 | return Arg; |
7762 | } |
7763 | |
7764 | switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) { |
7765 | case NPV_NotNullPointer: |
7766 | Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible) |
7767 | << Arg->getType() << ParamType; |
7768 | NoteTemplateParameterLocation(*Param); |
7769 | return ExprError(); |
7770 | |
7771 | case NPV_Error: |
7772 | return ExprError(); |
7773 | |
7774 | case NPV_NullPointer: |
7775 | Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); |
7776 | SugaredConverted = TemplateArgument(ParamType, |
7777 | /*isNullPtr=*/true); |
7778 | CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType), |
7779 | /*isNullPtr=*/true); |
7780 | return Arg; |
7781 | } |
7782 | } |
7783 | |
7784 | // -- For a non-type template-parameter of type pointer to data |
7785 | // member, qualification conversions (4.4) are applied. |
7786 | assert(ParamType->isMemberPointerType() && "Only pointers to members remain" ); |
7787 | |
7788 | if (CheckTemplateArgumentPointerToMember( |
7789 | S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted)) |
7790 | return ExprError(); |
7791 | return Arg; |
7792 | } |
7793 | |
7794 | static void DiagnoseTemplateParameterListArityMismatch( |
7795 | Sema &S, TemplateParameterList *New, TemplateParameterList *Old, |
7796 | Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc); |
7797 | |
7798 | /// Check a template argument against its corresponding |
7799 | /// template template parameter. |
7800 | /// |
7801 | /// This routine implements the semantics of C++ [temp.arg.template]. |
7802 | /// It returns true if an error occurred, and false otherwise. |
7803 | bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, |
7804 | TemplateParameterList *Params, |
7805 | TemplateArgumentLoc &Arg) { |
7806 | TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern(); |
7807 | TemplateDecl *Template = Name.getAsTemplateDecl(); |
7808 | if (!Template) { |
7809 | // Any dependent template name is fine. |
7810 | assert(Name.isDependent() && "Non-dependent template isn't a declaration?" ); |
7811 | return false; |
7812 | } |
7813 | |
7814 | if (Template->isInvalidDecl()) |
7815 | return true; |
7816 | |
7817 | // C++0x [temp.arg.template]p1: |
7818 | // A template-argument for a template template-parameter shall be |
7819 | // the name of a class template or an alias template, expressed as an |
7820 | // id-expression. When the template-argument names a class template, only |
7821 | // primary class templates are considered when matching the |
7822 | // template template argument with the corresponding parameter; |
7823 | // partial specializations are not considered even if their |
7824 | // parameter lists match that of the template template parameter. |
7825 | // |
7826 | // Note that we also allow template template parameters here, which |
7827 | // will happen when we are dealing with, e.g., class template |
7828 | // partial specializations. |
7829 | if (!isa<ClassTemplateDecl>(Val: Template) && |
7830 | !isa<TemplateTemplateParmDecl>(Val: Template) && |
7831 | !isa<TypeAliasTemplateDecl>(Val: Template) && |
7832 | !isa<BuiltinTemplateDecl>(Val: Template)) { |
7833 | assert(isa<FunctionTemplateDecl>(Template) && |
7834 | "Only function templates are possible here" ); |
7835 | Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template); |
7836 | Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) |
7837 | << Template; |
7838 | } |
7839 | |
7840 | // C++1z [temp.arg.template]p3: (DR 150) |
7841 | // A template-argument matches a template template-parameter P when P |
7842 | // is at least as specialized as the template-argument A. |
7843 | // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a |
7844 | // defect report resolution from C++17 and shouldn't be introduced by |
7845 | // concepts. |
7846 | if (getLangOpts().RelaxedTemplateTemplateArgs) { |
7847 | // Quick check for the common case: |
7848 | // If P contains a parameter pack, then A [...] matches P if each of A's |
7849 | // template parameters matches the corresponding template parameter in |
7850 | // the template-parameter-list of P. |
7851 | if (TemplateParameterListsAreEqual( |
7852 | New: Template->getTemplateParameters(), Old: Params, Complain: false, |
7853 | Kind: TPL_TemplateTemplateArgumentMatch, TemplateArgLoc: Arg.getLocation()) && |
7854 | // If the argument has no associated constraints, then the parameter is |
7855 | // definitely at least as specialized as the argument. |
7856 | // Otherwise - we need a more thorough check. |
7857 | !Template->hasAssociatedConstraints()) |
7858 | return false; |
7859 | |
7860 | if (isTemplateTemplateParameterAtLeastAsSpecializedAs(PParam: Params, AArg: Template, |
7861 | Loc: Arg.getLocation())) { |
7862 | // P2113 |
7863 | // C++20[temp.func.order]p2 |
7864 | // [...] If both deductions succeed, the partial ordering selects the |
7865 | // more constrained template (if one exists) as determined below. |
7866 | SmallVector<const Expr *, 3> ParamsAC, TemplateAC; |
7867 | Params->getAssociatedConstraints(AC&: ParamsAC); |
7868 | // C++2a[temp.arg.template]p3 |
7869 | // [...] In this comparison, if P is unconstrained, the constraints on A |
7870 | // are not considered. |
7871 | if (ParamsAC.empty()) |
7872 | return false; |
7873 | |
7874 | Template->getAssociatedConstraints(AC&: TemplateAC); |
7875 | |
7876 | bool IsParamAtLeastAsConstrained; |
7877 | if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC, |
7878 | IsParamAtLeastAsConstrained)) |
7879 | return true; |
7880 | if (!IsParamAtLeastAsConstrained) { |
7881 | Diag(Arg.getLocation(), |
7882 | diag::err_template_template_parameter_not_at_least_as_constrained) |
7883 | << Template << Param << Arg.getSourceRange(); |
7884 | Diag(Param->getLocation(), diag::note_entity_declared_at) << Param; |
7885 | Diag(Template->getLocation(), diag::note_entity_declared_at) |
7886 | << Template; |
7887 | MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template, |
7888 | TemplateAC); |
7889 | return true; |
7890 | } |
7891 | return false; |
7892 | } |
7893 | // FIXME: Produce better diagnostics for deduction failures. |
7894 | } |
7895 | |
7896 | return !TemplateParameterListsAreEqual(New: Template->getTemplateParameters(), |
7897 | Old: Params, |
7898 | Complain: true, |
7899 | Kind: TPL_TemplateTemplateArgumentMatch, |
7900 | TemplateArgLoc: Arg.getLocation()); |
7901 | } |
7902 | |
7903 | static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, |
7904 | unsigned HereDiagID, |
7905 | unsigned ExternalDiagID) { |
7906 | if (Decl.getLocation().isValid()) |
7907 | return S.Diag(Decl.getLocation(), HereDiagID); |
7908 | |
7909 | SmallString<128> Str; |
7910 | llvm::raw_svector_ostream Out(Str); |
7911 | PrintingPolicy PP = S.getPrintingPolicy(); |
7912 | PP.TerseOutput = 1; |
7913 | Decl.print(Out, PP); |
7914 | return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str(); |
7915 | } |
7916 | |
7917 | void Sema::NoteTemplateLocation(const NamedDecl &Decl, |
7918 | std::optional<SourceRange> ParamRange) { |
7919 | SemaDiagnosticBuilder DB = |
7920 | noteLocation(*this, Decl, diag::note_template_decl_here, |
7921 | diag::note_template_decl_external); |
7922 | if (ParamRange && ParamRange->isValid()) { |
7923 | assert(Decl.getLocation().isValid() && |
7924 | "Parameter range has location when Decl does not" ); |
7925 | DB << *ParamRange; |
7926 | } |
7927 | } |
7928 | |
7929 | void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) { |
7930 | noteLocation(*this, Decl, diag::note_template_param_here, |
7931 | diag::note_template_param_external); |
7932 | } |
7933 | |
7934 | /// Given a non-type template argument that refers to a |
7935 | /// declaration and the type of its corresponding non-type template |
7936 | /// parameter, produce an expression that properly refers to that |
7937 | /// declaration. |
7938 | ExprResult |
7939 | Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, |
7940 | QualType ParamType, |
7941 | SourceLocation Loc) { |
7942 | // C++ [temp.param]p8: |
7943 | // |
7944 | // A non-type template-parameter of type "array of T" or |
7945 | // "function returning T" is adjusted to be of type "pointer to |
7946 | // T" or "pointer to function returning T", respectively. |
7947 | if (ParamType->isArrayType()) |
7948 | ParamType = Context.getArrayDecayedType(T: ParamType); |
7949 | else if (ParamType->isFunctionType()) |
7950 | ParamType = Context.getPointerType(T: ParamType); |
7951 | |
7952 | // For a NULL non-type template argument, return nullptr casted to the |
7953 | // parameter's type. |
7954 | if (Arg.getKind() == TemplateArgument::NullPtr) { |
7955 | return ImpCastExprToType( |
7956 | new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc), |
7957 | ParamType, |
7958 | ParamType->getAs<MemberPointerType>() |
7959 | ? CK_NullToMemberPointer |
7960 | : CK_NullToPointer); |
7961 | } |
7962 | assert(Arg.getKind() == TemplateArgument::Declaration && |
7963 | "Only declaration template arguments permitted here" ); |
7964 | |
7965 | ValueDecl *VD = Arg.getAsDecl(); |
7966 | |
7967 | CXXScopeSpec SS; |
7968 | if (ParamType->isMemberPointerType()) { |
7969 | // If this is a pointer to member, we need to use a qualified name to |
7970 | // form a suitable pointer-to-member constant. |
7971 | assert(VD->getDeclContext()->isRecord() && |
7972 | (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || |
7973 | isa<IndirectFieldDecl>(VD))); |
7974 | QualType ClassType |
7975 | = Context.getTypeDeclType(Decl: cast<RecordDecl>(VD->getDeclContext())); |
7976 | NestedNameSpecifier *Qualifier |
7977 | = NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: false, |
7978 | T: ClassType.getTypePtr()); |
7979 | SS.MakeTrivial(Context, Qualifier, R: Loc); |
7980 | } |
7981 | |
7982 | ExprResult RefExpr = BuildDeclarationNameExpr( |
7983 | SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD); |
7984 | if (RefExpr.isInvalid()) |
7985 | return ExprError(); |
7986 | |
7987 | // For a pointer, the argument declaration is the pointee. Take its address. |
7988 | QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0); |
7989 | if (ParamType->isPointerType() && !ElemT.isNull() && |
7990 | Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) { |
7991 | // Decay an array argument if we want a pointer to its first element. |
7992 | RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get()); |
7993 | if (RefExpr.isInvalid()) |
7994 | return ExprError(); |
7995 | } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) { |
7996 | // For any other pointer, take the address (or form a pointer-to-member). |
7997 | RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get()); |
7998 | if (RefExpr.isInvalid()) |
7999 | return ExprError(); |
8000 | } else if (ParamType->isRecordType()) { |
8001 | assert(isa<TemplateParamObjectDecl>(VD) && |
8002 | "arg for class template param not a template parameter object" ); |
8003 | // No conversions apply in this case. |
8004 | return RefExpr; |
8005 | } else { |
8006 | assert(ParamType->isReferenceType() && |
8007 | "unexpected type for decl template argument" ); |
8008 | } |
8009 | |
8010 | // At this point we should have the right value category. |
8011 | assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() && |
8012 | "value kind mismatch for non-type template argument" ); |
8013 | |
8014 | // The type of the template parameter can differ from the type of the |
8015 | // argument in various ways; convert it now if necessary. |
8016 | QualType DestExprType = ParamType.getNonLValueExprType(Context); |
8017 | if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) { |
8018 | CastKind CK; |
8019 | QualType Ignored; |
8020 | if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) || |
8021 | IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType, ResultTy&: Ignored)) { |
8022 | CK = CK_NoOp; |
8023 | } else if (ParamType->isVoidPointerType() && |
8024 | RefExpr.get()->getType()->isPointerType()) { |
8025 | CK = CK_BitCast; |
8026 | } else { |
8027 | // FIXME: Pointers to members can need conversion derived-to-base or |
8028 | // base-to-derived conversions. We currently don't retain enough |
8029 | // information to convert properly (we need to track a cast path or |
8030 | // subobject number in the template argument). |
8031 | llvm_unreachable( |
8032 | "unexpected conversion required for non-type template argument" ); |
8033 | } |
8034 | RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK, |
8035 | VK: RefExpr.get()->getValueKind()); |
8036 | } |
8037 | |
8038 | return RefExpr; |
8039 | } |
8040 | |
8041 | /// Construct a new expression that refers to the given |
8042 | /// integral template argument with the given source-location |
8043 | /// information. |
8044 | /// |
8045 | /// This routine takes care of the mapping from an integral template |
8046 | /// argument (which may have any integral type) to the appropriate |
8047 | /// literal value. |
8048 | static Expr *BuildExpressionFromIntegralTemplateArgumentValue( |
8049 | Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) { |
8050 | assert(OrigT->isIntegralOrEnumerationType()); |
8051 | |
8052 | // If this is an enum type that we're instantiating, we need to use an integer |
8053 | // type the same size as the enumerator. We don't want to build an |
8054 | // IntegerLiteral with enum type. The integer type of an enum type can be of |
8055 | // any integral type with C++11 enum classes, make sure we create the right |
8056 | // type of literal for it. |
8057 | QualType T = OrigT; |
8058 | if (const EnumType *ET = OrigT->getAs<EnumType>()) |
8059 | T = ET->getDecl()->getIntegerType(); |
8060 | |
8061 | Expr *E; |
8062 | if (T->isAnyCharacterType()) { |
8063 | CharacterLiteralKind Kind; |
8064 | if (T->isWideCharType()) |
8065 | Kind = CharacterLiteralKind::Wide; |
8066 | else if (T->isChar8Type() && S.getLangOpts().Char8) |
8067 | Kind = CharacterLiteralKind::UTF8; |
8068 | else if (T->isChar16Type()) |
8069 | Kind = CharacterLiteralKind::UTF16; |
8070 | else if (T->isChar32Type()) |
8071 | Kind = CharacterLiteralKind::UTF32; |
8072 | else |
8073 | Kind = CharacterLiteralKind::Ascii; |
8074 | |
8075 | E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc); |
8076 | } else if (T->isBooleanType()) { |
8077 | E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc); |
8078 | } else { |
8079 | E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc); |
8080 | } |
8081 | |
8082 | if (OrigT->isEnumeralType()) { |
8083 | // FIXME: This is a hack. We need a better way to handle substituted |
8084 | // non-type template parameters. |
8085 | E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E, |
8086 | BasePath: nullptr, FPO: S.CurFPFeatureOverrides(), |
8087 | WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc), |
8088 | L: Loc, R: Loc); |
8089 | } |
8090 | |
8091 | return E; |
8092 | } |
8093 | |
8094 | static Expr *BuildExpressionFromNonTypeTemplateArgumentValue( |
8095 | Sema &S, QualType T, const APValue &Val, SourceLocation Loc) { |
8096 | auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * { |
8097 | auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc); |
8098 | ILE->setType(T); |
8099 | return ILE; |
8100 | }; |
8101 | |
8102 | switch (Val.getKind()) { |
8103 | case APValue::AddrLabelDiff: |
8104 | // This cannot occur in a template argument at all. |
8105 | case APValue::Array: |
8106 | case APValue::Struct: |
8107 | case APValue::Union: |
8108 | // These can only occur within a template parameter object, which is |
8109 | // represented as a TemplateArgument::Declaration. |
8110 | llvm_unreachable("unexpected template argument value" ); |
8111 | |
8112 | case APValue::Int: |
8113 | return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(), |
8114 | Loc); |
8115 | |
8116 | case APValue::Float: |
8117 | return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true, |
8118 | Type: T, L: Loc); |
8119 | |
8120 | case APValue::FixedPoint: |
8121 | return FixedPointLiteral::CreateFromRawInt( |
8122 | C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc, |
8123 | Scale: Val.getFixedPoint().getScale()); |
8124 | |
8125 | case APValue::ComplexInt: { |
8126 | QualType ElemT = T->castAs<ComplexType>()->getElementType(); |
8127 | return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue( |
8128 | S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc), |
8129 | BuildExpressionFromIntegralTemplateArgumentValue( |
8130 | S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)}); |
8131 | } |
8132 | |
8133 | case APValue::ComplexFloat: { |
8134 | QualType ElemT = T->castAs<ComplexType>()->getElementType(); |
8135 | return MakeInitList( |
8136 | {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true, |
8137 | Type: ElemT, L: Loc), |
8138 | FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true, |
8139 | Type: ElemT, L: Loc)}); |
8140 | } |
8141 | |
8142 | case APValue::Vector: { |
8143 | QualType ElemT = T->castAs<VectorType>()->getElementType(); |
8144 | llvm::SmallVector<Expr *, 8> Elts; |
8145 | for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I) |
8146 | Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue( |
8147 | S, T: ElemT, Val: Val.getVectorElt(I), Loc)); |
8148 | return MakeInitList(Elts); |
8149 | } |
8150 | |
8151 | case APValue::None: |
8152 | case APValue::Indeterminate: |
8153 | llvm_unreachable("Unexpected APValue kind." ); |
8154 | case APValue::LValue: |
8155 | case APValue::MemberPointer: |
8156 | // There isn't necessarily a valid equivalent source-level syntax for |
8157 | // these; in particular, a naive lowering might violate access control. |
8158 | // So for now we lower to a ConstantExpr holding the value, wrapped around |
8159 | // an OpaqueValueExpr. |
8160 | // FIXME: We should have a better representation for this. |
8161 | ExprValueKind VK = VK_PRValue; |
8162 | if (T->isReferenceType()) { |
8163 | T = T->getPointeeType(); |
8164 | VK = VK_LValue; |
8165 | } |
8166 | auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK); |
8167 | return ConstantExpr::Create(S.Context, OVE, Val); |
8168 | } |
8169 | llvm_unreachable("Unhandled APValue::ValueKind enum" ); |
8170 | } |
8171 | |
8172 | ExprResult |
8173 | Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, |
8174 | SourceLocation Loc) { |
8175 | switch (Arg.getKind()) { |
8176 | case TemplateArgument::Null: |
8177 | case TemplateArgument::Type: |
8178 | case TemplateArgument::Template: |
8179 | case TemplateArgument::TemplateExpansion: |
8180 | case TemplateArgument::Pack: |
8181 | llvm_unreachable("not a non-type template argument" ); |
8182 | |
8183 | case TemplateArgument::Expression: |
8184 | return Arg.getAsExpr(); |
8185 | |
8186 | case TemplateArgument::NullPtr: |
8187 | case TemplateArgument::Declaration: |
8188 | return BuildExpressionFromDeclTemplateArgument( |
8189 | Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc); |
8190 | |
8191 | case TemplateArgument::Integral: |
8192 | return BuildExpressionFromIntegralTemplateArgumentValue( |
8193 | S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc); |
8194 | |
8195 | case TemplateArgument::StructuralValue: |
8196 | return BuildExpressionFromNonTypeTemplateArgumentValue( |
8197 | S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc); |
8198 | } |
8199 | llvm_unreachable("Unhandled TemplateArgument::ArgKind enum" ); |
8200 | } |
8201 | |
8202 | /// Match two template parameters within template parameter lists. |
8203 | static bool MatchTemplateParameterKind( |
8204 | Sema &S, NamedDecl *New, |
8205 | const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, |
8206 | const NamedDecl *OldInstFrom, bool Complain, |
8207 | Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { |
8208 | // Check the actual kind (type, non-type, template). |
8209 | if (Old->getKind() != New->getKind()) { |
8210 | if (Complain) { |
8211 | unsigned NextDiag = diag::err_template_param_different_kind; |
8212 | if (TemplateArgLoc.isValid()) { |
8213 | S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); |
8214 | NextDiag = diag::note_template_param_different_kind; |
8215 | } |
8216 | S.Diag(New->getLocation(), NextDiag) |
8217 | << (Kind != Sema::TPL_TemplateMatch); |
8218 | S.Diag(Old->getLocation(), diag::note_template_prev_declaration) |
8219 | << (Kind != Sema::TPL_TemplateMatch); |
8220 | } |
8221 | |
8222 | return false; |
8223 | } |
8224 | |
8225 | // Check that both are parameter packs or neither are parameter packs. |
8226 | // However, if we are matching a template template argument to a |
8227 | // template template parameter, the template template parameter can have |
8228 | // a parameter pack where the template template argument does not. |
8229 | if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && |
8230 | !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && |
8231 | Old->isTemplateParameterPack())) { |
8232 | if (Complain) { |
8233 | unsigned NextDiag = diag::err_template_parameter_pack_non_pack; |
8234 | if (TemplateArgLoc.isValid()) { |
8235 | S.Diag(TemplateArgLoc, |
8236 | diag::err_template_arg_template_params_mismatch); |
8237 | NextDiag = diag::note_template_parameter_pack_non_pack; |
8238 | } |
8239 | |
8240 | unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0 |
8241 | : isa<NonTypeTemplateParmDecl>(Val: New)? 1 |
8242 | : 2; |
8243 | S.Diag(New->getLocation(), NextDiag) |
8244 | << ParamKind << New->isParameterPack(); |
8245 | S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) |
8246 | << ParamKind << Old->isParameterPack(); |
8247 | } |
8248 | |
8249 | return false; |
8250 | } |
8251 | |
8252 | // For non-type template parameters, check the type of the parameter. |
8253 | if (NonTypeTemplateParmDecl *OldNTTP |
8254 | = dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) { |
8255 | NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New); |
8256 | |
8257 | // If we are matching a template template argument to a template |
8258 | // template parameter and one of the non-type template parameter types |
8259 | // is dependent, then we must wait until template instantiation time |
8260 | // to actually compare the arguments. |
8261 | if (Kind != Sema::TPL_TemplateTemplateArgumentMatch || |
8262 | (!OldNTTP->getType()->isDependentType() && |
8263 | !NewNTTP->getType()->isDependentType())) { |
8264 | // C++20 [temp.over.link]p6: |
8265 | // Two [non-type] template-parameters are equivalent [if] they have |
8266 | // equivalent types ignoring the use of type-constraints for |
8267 | // placeholder types |
8268 | QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType()); |
8269 | QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType()); |
8270 | if (!S.Context.hasSameType(T1: OldType, T2: NewType)) { |
8271 | if (Complain) { |
8272 | unsigned NextDiag = diag::err_template_nontype_parm_different_type; |
8273 | if (TemplateArgLoc.isValid()) { |
8274 | S.Diag(TemplateArgLoc, |
8275 | diag::err_template_arg_template_params_mismatch); |
8276 | NextDiag = diag::note_template_nontype_parm_different_type; |
8277 | } |
8278 | S.Diag(NewNTTP->getLocation(), NextDiag) |
8279 | << NewNTTP->getType() |
8280 | << (Kind != Sema::TPL_TemplateMatch); |
8281 | S.Diag(OldNTTP->getLocation(), |
8282 | diag::note_template_nontype_parm_prev_declaration) |
8283 | << OldNTTP->getType(); |
8284 | } |
8285 | |
8286 | return false; |
8287 | } |
8288 | } |
8289 | } |
8290 | // For template template parameters, check the template parameter types. |
8291 | // The template parameter lists of template template |
8292 | // parameters must agree. |
8293 | else if (TemplateTemplateParmDecl *OldTTP = |
8294 | dyn_cast<TemplateTemplateParmDecl>(Val: Old)) { |
8295 | TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New); |
8296 | if (!S.TemplateParameterListsAreEqual( |
8297 | NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom, |
8298 | OldTTP->getTemplateParameters(), Complain, |
8299 | (Kind == Sema::TPL_TemplateMatch |
8300 | ? Sema::TPL_TemplateTemplateParmMatch |
8301 | : Kind), |
8302 | TemplateArgLoc)) |
8303 | return false; |
8304 | } |
8305 | |
8306 | if (Kind != Sema::TPL_TemplateParamsEquivalent && |
8307 | Kind != Sema::TPL_TemplateTemplateArgumentMatch && |
8308 | !isa<TemplateTemplateParmDecl>(Val: Old)) { |
8309 | const Expr *NewC = nullptr, *OldC = nullptr; |
8310 | |
8311 | if (isa<TemplateTypeParmDecl>(Val: New)) { |
8312 | if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint()) |
8313 | NewC = TC->getImmediatelyDeclaredConstraint(); |
8314 | if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint()) |
8315 | OldC = TC->getImmediatelyDeclaredConstraint(); |
8316 | } else if (isa<NonTypeTemplateParmDecl>(Val: New)) { |
8317 | if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New) |
8318 | ->getPlaceholderTypeConstraint()) |
8319 | NewC = E; |
8320 | if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old) |
8321 | ->getPlaceholderTypeConstraint()) |
8322 | OldC = E; |
8323 | } else |
8324 | llvm_unreachable("unexpected template parameter type" ); |
8325 | |
8326 | auto Diagnose = [&] { |
8327 | S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(), |
8328 | diag::err_template_different_type_constraint); |
8329 | S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(), |
8330 | diag::note_template_prev_declaration) << /*declaration*/0; |
8331 | }; |
8332 | |
8333 | if (!NewC != !OldC) { |
8334 | if (Complain) |
8335 | Diagnose(); |
8336 | return false; |
8337 | } |
8338 | |
8339 | if (NewC) { |
8340 | if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom, |
8341 | NewConstr: NewC)) { |
8342 | if (Complain) |
8343 | Diagnose(); |
8344 | return false; |
8345 | } |
8346 | } |
8347 | } |
8348 | |
8349 | return true; |
8350 | } |
8351 | |
8352 | /// Diagnose a known arity mismatch when comparing template argument |
8353 | /// lists. |
8354 | static |
8355 | void DiagnoseTemplateParameterListArityMismatch(Sema &S, |
8356 | TemplateParameterList *New, |
8357 | TemplateParameterList *Old, |
8358 | Sema::TemplateParameterListEqualKind Kind, |
8359 | SourceLocation TemplateArgLoc) { |
8360 | unsigned NextDiag = diag::err_template_param_list_different_arity; |
8361 | if (TemplateArgLoc.isValid()) { |
8362 | S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); |
8363 | NextDiag = diag::note_template_param_list_different_arity; |
8364 | } |
8365 | S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag) |
8366 | << (New->size() > Old->size()) |
8367 | << (Kind != Sema::TPL_TemplateMatch) |
8368 | << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); |
8369 | S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) |
8370 | << (Kind != Sema::TPL_TemplateMatch) |
8371 | << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); |
8372 | } |
8373 | |
8374 | /// Determine whether the given template parameter lists are |
8375 | /// equivalent. |
8376 | /// |
8377 | /// \param New The new template parameter list, typically written in the |
8378 | /// source code as part of a new template declaration. |
8379 | /// |
8380 | /// \param Old The old template parameter list, typically found via |
8381 | /// name lookup of the template declared with this template parameter |
8382 | /// list. |
8383 | /// |
8384 | /// \param Complain If true, this routine will produce a diagnostic if |
8385 | /// the template parameter lists are not equivalent. |
8386 | /// |
8387 | /// \param Kind describes how we are to match the template parameter lists. |
8388 | /// |
8389 | /// \param TemplateArgLoc If this source location is valid, then we |
8390 | /// are actually checking the template parameter list of a template |
8391 | /// argument (New) against the template parameter list of its |
8392 | /// corresponding template template parameter (Old). We produce |
8393 | /// slightly different diagnostics in this scenario. |
8394 | /// |
8395 | /// \returns True if the template parameter lists are equal, false |
8396 | /// otherwise. |
8397 | bool Sema::TemplateParameterListsAreEqual( |
8398 | const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, |
8399 | const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, |
8400 | TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { |
8401 | if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { |
8402 | if (Complain) |
8403 | DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind, |
8404 | TemplateArgLoc); |
8405 | |
8406 | return false; |
8407 | } |
8408 | |
8409 | // C++0x [temp.arg.template]p3: |
8410 | // A template-argument matches a template template-parameter (call it P) |
8411 | // when each of the template parameters in the template-parameter-list of |
8412 | // the template-argument's corresponding class template or alias template |
8413 | // (call it A) matches the corresponding template parameter in the |
8414 | // template-parameter-list of P. [...] |
8415 | TemplateParameterList::iterator NewParm = New->begin(); |
8416 | TemplateParameterList::iterator NewParmEnd = New->end(); |
8417 | for (TemplateParameterList::iterator OldParm = Old->begin(), |
8418 | OldParmEnd = Old->end(); |
8419 | OldParm != OldParmEnd; ++OldParm) { |
8420 | if (Kind != TPL_TemplateTemplateArgumentMatch || |
8421 | !(*OldParm)->isTemplateParameterPack()) { |
8422 | if (NewParm == NewParmEnd) { |
8423 | if (Complain) |
8424 | DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind, |
8425 | TemplateArgLoc); |
8426 | |
8427 | return false; |
8428 | } |
8429 | |
8430 | if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm, |
8431 | OldInstFrom, Complain, Kind, |
8432 | TemplateArgLoc)) |
8433 | return false; |
8434 | |
8435 | ++NewParm; |
8436 | continue; |
8437 | } |
8438 | |
8439 | // C++0x [temp.arg.template]p3: |
8440 | // [...] When P's template- parameter-list contains a template parameter |
8441 | // pack (14.5.3), the template parameter pack will match zero or more |
8442 | // template parameters or template parameter packs in the |
8443 | // template-parameter-list of A with the same type and form as the |
8444 | // template parameter pack in P (ignoring whether those template |
8445 | // parameters are template parameter packs). |
8446 | for (; NewParm != NewParmEnd; ++NewParm) { |
8447 | if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm, |
8448 | OldInstFrom, Complain, Kind, |
8449 | TemplateArgLoc)) |
8450 | return false; |
8451 | } |
8452 | } |
8453 | |
8454 | // Make sure we exhausted all of the arguments. |
8455 | if (NewParm != NewParmEnd) { |
8456 | if (Complain) |
8457 | DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind, |
8458 | TemplateArgLoc); |
8459 | |
8460 | return false; |
8461 | } |
8462 | |
8463 | if (Kind != TPL_TemplateTemplateArgumentMatch && |
8464 | Kind != TPL_TemplateParamsEquivalent) { |
8465 | const Expr *NewRC = New->getRequiresClause(); |
8466 | const Expr *OldRC = Old->getRequiresClause(); |
8467 | |
8468 | auto Diagnose = [&] { |
8469 | Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(), |
8470 | diag::err_template_different_requires_clause); |
8471 | Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(), |
8472 | diag::note_template_prev_declaration) << /*declaration*/0; |
8473 | }; |
8474 | |
8475 | if (!NewRC != !OldRC) { |
8476 | if (Complain) |
8477 | Diagnose(); |
8478 | return false; |
8479 | } |
8480 | |
8481 | if (NewRC) { |
8482 | if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom, |
8483 | NewConstr: NewRC)) { |
8484 | if (Complain) |
8485 | Diagnose(); |
8486 | return false; |
8487 | } |
8488 | } |
8489 | } |
8490 | |
8491 | return true; |
8492 | } |
8493 | |
8494 | /// Check whether a template can be declared within this scope. |
8495 | /// |
8496 | /// If the template declaration is valid in this scope, returns |
8497 | /// false. Otherwise, issues a diagnostic and returns true. |
8498 | bool |
8499 | Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { |
8500 | if (!S) |
8501 | return false; |
8502 | |
8503 | // Find the nearest enclosing declaration scope. |
8504 | while ((S->getFlags() & Scope::DeclScope) == 0 || |
8505 | (S->getFlags() & Scope::TemplateParamScope) != 0) |
8506 | S = S->getParent(); |
8507 | |
8508 | // C++ [temp.pre]p6: [P2096] |
8509 | // A template, explicit specialization, or partial specialization shall not |
8510 | // have C linkage. |
8511 | DeclContext *Ctx = S->getEntity(); |
8512 | if (Ctx && Ctx->isExternCContext()) { |
8513 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) |
8514 | << TemplateParams->getSourceRange(); |
8515 | if (const LinkageSpecDecl *LSD = Ctx->getExternCContext()) |
8516 | Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); |
8517 | return true; |
8518 | } |
8519 | Ctx = Ctx ? Ctx->getRedeclContext() : nullptr; |
8520 | |
8521 | // C++ [temp]p2: |
8522 | // A template-declaration can appear only as a namespace scope or |
8523 | // class scope declaration. |
8524 | // C++ [temp.expl.spec]p3: |
8525 | // An explicit specialization may be declared in any scope in which the |
8526 | // corresponding primary template may be defined. |
8527 | // C++ [temp.class.spec]p6: [P2096] |
8528 | // A partial specialization may be declared in any scope in which the |
8529 | // corresponding primary template may be defined. |
8530 | if (Ctx) { |
8531 | if (Ctx->isFileContext()) |
8532 | return false; |
8533 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) { |
8534 | // C++ [temp.mem]p2: |
8535 | // A local class shall not have member templates. |
8536 | if (RD->isLocalClass()) |
8537 | return Diag(TemplateParams->getTemplateLoc(), |
8538 | diag::err_template_inside_local_class) |
8539 | << TemplateParams->getSourceRange(); |
8540 | else |
8541 | return false; |
8542 | } |
8543 | } |
8544 | |
8545 | return Diag(TemplateParams->getTemplateLoc(), |
8546 | diag::err_template_outside_namespace_or_class_scope) |
8547 | << TemplateParams->getSourceRange(); |
8548 | } |
8549 | |
8550 | /// Determine what kind of template specialization the given declaration |
8551 | /// is. |
8552 | static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) { |
8553 | if (!D) |
8554 | return TSK_Undeclared; |
8555 | |
8556 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) |
8557 | return Record->getTemplateSpecializationKind(); |
8558 | if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D)) |
8559 | return Function->getTemplateSpecializationKind(); |
8560 | if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) |
8561 | return Var->getTemplateSpecializationKind(); |
8562 | |
8563 | return TSK_Undeclared; |
8564 | } |
8565 | |
8566 | /// Check whether a specialization is well-formed in the current |
8567 | /// context. |
8568 | /// |
8569 | /// This routine determines whether a template specialization can be declared |
8570 | /// in the current context (C++ [temp.expl.spec]p2). |
8571 | /// |
8572 | /// \param S the semantic analysis object for which this check is being |
8573 | /// performed. |
8574 | /// |
8575 | /// \param Specialized the entity being specialized or instantiated, which |
8576 | /// may be a kind of template (class template, function template, etc.) or |
8577 | /// a member of a class template (member function, static data member, |
8578 | /// member class). |
8579 | /// |
8580 | /// \param PrevDecl the previous declaration of this entity, if any. |
8581 | /// |
8582 | /// \param Loc the location of the explicit specialization or instantiation of |
8583 | /// this entity. |
8584 | /// |
8585 | /// \param IsPartialSpecialization whether this is a partial specialization of |
8586 | /// a class template. |
8587 | /// |
8588 | /// \returns true if there was an error that we cannot recover from, false |
8589 | /// otherwise. |
8590 | static bool CheckTemplateSpecializationScope(Sema &S, |
8591 | NamedDecl *Specialized, |
8592 | NamedDecl *PrevDecl, |
8593 | SourceLocation Loc, |
8594 | bool IsPartialSpecialization) { |
8595 | // Keep these "kind" numbers in sync with the %select statements in the |
8596 | // various diagnostics emitted by this routine. |
8597 | int EntityKind = 0; |
8598 | if (isa<ClassTemplateDecl>(Val: Specialized)) |
8599 | EntityKind = IsPartialSpecialization? 1 : 0; |
8600 | else if (isa<VarTemplateDecl>(Val: Specialized)) |
8601 | EntityKind = IsPartialSpecialization ? 3 : 2; |
8602 | else if (isa<FunctionTemplateDecl>(Val: Specialized)) |
8603 | EntityKind = 4; |
8604 | else if (isa<CXXMethodDecl>(Val: Specialized)) |
8605 | EntityKind = 5; |
8606 | else if (isa<VarDecl>(Val: Specialized)) |
8607 | EntityKind = 6; |
8608 | else if (isa<RecordDecl>(Val: Specialized)) |
8609 | EntityKind = 7; |
8610 | else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11) |
8611 | EntityKind = 8; |
8612 | else { |
8613 | S.Diag(Loc, diag::err_template_spec_unknown_kind) |
8614 | << S.getLangOpts().CPlusPlus11; |
8615 | S.Diag(Specialized->getLocation(), diag::note_specialized_entity); |
8616 | return true; |
8617 | } |
8618 | |
8619 | // C++ [temp.expl.spec]p2: |
8620 | // An explicit specialization may be declared in any scope in which |
8621 | // the corresponding primary template may be defined. |
8622 | if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { |
8623 | S.Diag(Loc, diag::err_template_spec_decl_function_scope) |
8624 | << Specialized; |
8625 | return true; |
8626 | } |
8627 | |
8628 | // C++ [temp.class.spec]p6: |
8629 | // A class template partial specialization may be declared in any |
8630 | // scope in which the primary template may be defined. |
8631 | DeclContext *SpecializedContext = |
8632 | Specialized->getDeclContext()->getRedeclContext(); |
8633 | DeclContext *DC = S.CurContext->getRedeclContext(); |
8634 | |
8635 | // Make sure that this redeclaration (or definition) occurs in the same |
8636 | // scope or an enclosing namespace. |
8637 | if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext) |
8638 | : DC->Equals(DC: SpecializedContext))) { |
8639 | if (isa<TranslationUnitDecl>(Val: SpecializedContext)) |
8640 | S.Diag(Loc, diag::err_template_spec_redecl_global_scope) |
8641 | << EntityKind << Specialized; |
8642 | else { |
8643 | auto *ND = cast<NamedDecl>(Val: SpecializedContext); |
8644 | int Diag = diag::err_template_spec_redecl_out_of_scope; |
8645 | if (S.getLangOpts().MicrosoftExt && !DC->isRecord()) |
8646 | Diag = diag::ext_ms_template_spec_redecl_out_of_scope; |
8647 | S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized |
8648 | << ND << isa<CXXRecordDecl>(ND); |
8649 | } |
8650 | |
8651 | S.Diag(Specialized->getLocation(), diag::note_specialized_entity); |
8652 | |
8653 | // Don't allow specializing in the wrong class during error recovery. |
8654 | // Otherwise, things can go horribly wrong. |
8655 | if (DC->isRecord()) |
8656 | return true; |
8657 | } |
8658 | |
8659 | return false; |
8660 | } |
8661 | |
8662 | static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) { |
8663 | if (!E->isTypeDependent()) |
8664 | return SourceLocation(); |
8665 | DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); |
8666 | Checker.TraverseStmt(E); |
8667 | if (Checker.MatchLoc.isInvalid()) |
8668 | return E->getSourceRange(); |
8669 | return Checker.MatchLoc; |
8670 | } |
8671 | |
8672 | static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) { |
8673 | if (!TL.getType()->isDependentType()) |
8674 | return SourceLocation(); |
8675 | DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); |
8676 | Checker.TraverseTypeLoc(TL); |
8677 | if (Checker.MatchLoc.isInvalid()) |
8678 | return TL.getSourceRange(); |
8679 | return Checker.MatchLoc; |
8680 | } |
8681 | |
8682 | /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs |
8683 | /// that checks non-type template partial specialization arguments. |
8684 | static bool CheckNonTypeTemplatePartialSpecializationArgs( |
8685 | Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, |
8686 | const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) { |
8687 | for (unsigned I = 0; I != NumArgs; ++I) { |
8688 | if (Args[I].getKind() == TemplateArgument::Pack) { |
8689 | if (CheckNonTypeTemplatePartialSpecializationArgs( |
8690 | S, TemplateNameLoc, Param, Args: Args[I].pack_begin(), |
8691 | NumArgs: Args[I].pack_size(), IsDefaultArgument)) |
8692 | return true; |
8693 | |
8694 | continue; |
8695 | } |
8696 | |
8697 | if (Args[I].getKind() != TemplateArgument::Expression) |
8698 | continue; |
8699 | |
8700 | Expr *ArgExpr = Args[I].getAsExpr(); |
8701 | |
8702 | // We can have a pack expansion of any of the bullets below. |
8703 | if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr)) |
8704 | ArgExpr = Expansion->getPattern(); |
8705 | |
8706 | // Strip off any implicit casts we added as part of type checking. |
8707 | while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr)) |
8708 | ArgExpr = ICE->getSubExpr(); |
8709 | |
8710 | // C++ [temp.class.spec]p8: |
8711 | // A non-type argument is non-specialized if it is the name of a |
8712 | // non-type parameter. All other non-type arguments are |
8713 | // specialized. |
8714 | // |
8715 | // Below, we check the two conditions that only apply to |
8716 | // specialized non-type arguments, so skip any non-specialized |
8717 | // arguments. |
8718 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr)) |
8719 | if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl())) |
8720 | continue; |
8721 | |
8722 | // C++ [temp.class.spec]p9: |
8723 | // Within the argument list of a class template partial |
8724 | // specialization, the following restrictions apply: |
8725 | // -- A partially specialized non-type argument expression |
8726 | // shall not involve a template parameter of the partial |
8727 | // specialization except when the argument expression is a |
8728 | // simple identifier. |
8729 | // -- The type of a template parameter corresponding to a |
8730 | // specialized non-type argument shall not be dependent on a |
8731 | // parameter of the specialization. |
8732 | // DR1315 removes the first bullet, leaving an incoherent set of rules. |
8733 | // We implement a compromise between the original rules and DR1315: |
8734 | // -- A specialized non-type template argument shall not be |
8735 | // type-dependent and the corresponding template parameter |
8736 | // shall have a non-dependent type. |
8737 | SourceRange ParamUseRange = |
8738 | findTemplateParameterInType(Param->getDepth(), ArgExpr); |
8739 | if (ParamUseRange.isValid()) { |
8740 | if (IsDefaultArgument) { |
8741 | S.Diag(TemplateNameLoc, |
8742 | diag::err_dependent_non_type_arg_in_partial_spec); |
8743 | S.Diag(ParamUseRange.getBegin(), |
8744 | diag::note_dependent_non_type_default_arg_in_partial_spec) |
8745 | << ParamUseRange; |
8746 | } else { |
8747 | S.Diag(ParamUseRange.getBegin(), |
8748 | diag::err_dependent_non_type_arg_in_partial_spec) |
8749 | << ParamUseRange; |
8750 | } |
8751 | return true; |
8752 | } |
8753 | |
8754 | ParamUseRange = findTemplateParameter( |
8755 | Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc()); |
8756 | if (ParamUseRange.isValid()) { |
8757 | S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(), |
8758 | diag::err_dependent_typed_non_type_arg_in_partial_spec) |
8759 | << Param->getType(); |
8760 | S.NoteTemplateParameterLocation(*Param); |
8761 | return true; |
8762 | } |
8763 | } |
8764 | |
8765 | return false; |
8766 | } |
8767 | |
8768 | /// Check the non-type template arguments of a class template |
8769 | /// partial specialization according to C++ [temp.class.spec]p9. |
8770 | /// |
8771 | /// \param TemplateNameLoc the location of the template name. |
8772 | /// \param PrimaryTemplate the template parameters of the primary class |
8773 | /// template. |
8774 | /// \param NumExplicit the number of explicitly-specified template arguments. |
8775 | /// \param TemplateArgs the template arguments of the class template |
8776 | /// partial specialization. |
8777 | /// |
8778 | /// \returns \c true if there was an error, \c false otherwise. |
8779 | bool Sema::CheckTemplatePartialSpecializationArgs( |
8780 | SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate, |
8781 | unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) { |
8782 | // We have to be conservative when checking a template in a dependent |
8783 | // context. |
8784 | if (PrimaryTemplate->getDeclContext()->isDependentContext()) |
8785 | return false; |
8786 | |
8787 | TemplateParameterList *TemplateParams = |
8788 | PrimaryTemplate->getTemplateParameters(); |
8789 | for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { |
8790 | NonTypeTemplateParmDecl *Param |
8791 | = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I)); |
8792 | if (!Param) |
8793 | continue; |
8794 | |
8795 | if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc, |
8796 | Param, Args: &TemplateArgs[I], |
8797 | NumArgs: 1, IsDefaultArgument: I >= NumExplicit)) |
8798 | return true; |
8799 | } |
8800 | |
8801 | return false; |
8802 | } |
8803 | |
8804 | DeclResult Sema::ActOnClassTemplateSpecialization( |
8805 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
8806 | SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, |
8807 | TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, |
8808 | MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) { |
8809 | assert(TUK != TUK_Reference && "References are not specializations" ); |
8810 | |
8811 | // NOTE: KWLoc is the location of the tag keyword. This will instead |
8812 | // store the location of the outermost template keyword in the declaration. |
8813 | SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0 |
8814 | ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc; |
8815 | SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc; |
8816 | SourceLocation LAngleLoc = TemplateId.LAngleLoc; |
8817 | SourceLocation RAngleLoc = TemplateId.RAngleLoc; |
8818 | |
8819 | // Find the class template we're specializing |
8820 | TemplateName Name = TemplateId.Template.get(); |
8821 | ClassTemplateDecl *ClassTemplate |
8822 | = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl()); |
8823 | |
8824 | if (!ClassTemplate) { |
8825 | Diag(TemplateNameLoc, diag::err_not_class_template_specialization) |
8826 | << (Name.getAsTemplateDecl() && |
8827 | isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); |
8828 | return true; |
8829 | } |
8830 | |
8831 | bool isMemberSpecialization = false; |
8832 | bool isPartialSpecialization = false; |
8833 | |
8834 | if (SS.isSet()) { |
8835 | if (TUK != TUK_Reference && TUK != TUK_Friend && |
8836 | diagnoseQualifiedDeclaration(SS, DC: ClassTemplate->getDeclContext(), |
8837 | Name: ClassTemplate->getDeclName(), |
8838 | Loc: TemplateNameLoc, TemplateId: &TemplateId, |
8839 | /*IsMemberSpecialization=*/false)) |
8840 | return true; |
8841 | } |
8842 | |
8843 | // Check the validity of the template headers that introduce this |
8844 | // template. |
8845 | // FIXME: We probably shouldn't complain about these headers for |
8846 | // friend declarations. |
8847 | bool Invalid = false; |
8848 | TemplateParameterList *TemplateParams = |
8849 | MatchTemplateParametersToScopeSpecifier( |
8850 | DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, |
8851 | ParamLists: TemplateParameterLists, IsFriend: TUK == TUK_Friend, IsMemberSpecialization&: isMemberSpecialization, |
8852 | Invalid); |
8853 | if (Invalid) |
8854 | return true; |
8855 | |
8856 | // Check that we can declare a template specialization here. |
8857 | if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams)) |
8858 | return true; |
8859 | |
8860 | if (TemplateParams && TemplateParams->size() > 0) { |
8861 | isPartialSpecialization = true; |
8862 | |
8863 | if (TUK == TUK_Friend) { |
8864 | Diag(KWLoc, diag::err_partial_specialization_friend) |
8865 | << SourceRange(LAngleLoc, RAngleLoc); |
8866 | return true; |
8867 | } |
8868 | |
8869 | // C++ [temp.class.spec]p10: |
8870 | // The template parameter list of a specialization shall not |
8871 | // contain default template argument values. |
8872 | for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { |
8873 | Decl *Param = TemplateParams->getParam(Idx: I); |
8874 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) { |
8875 | if (TTP->hasDefaultArgument()) { |
8876 | Diag(TTP->getDefaultArgumentLoc(), |
8877 | diag::err_default_arg_in_partial_spec); |
8878 | TTP->removeDefaultArgument(); |
8879 | } |
8880 | } else if (NonTypeTemplateParmDecl *NTTP |
8881 | = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) { |
8882 | if (Expr *DefArg = NTTP->getDefaultArgument()) { |
8883 | Diag(NTTP->getDefaultArgumentLoc(), |
8884 | diag::err_default_arg_in_partial_spec) |
8885 | << DefArg->getSourceRange(); |
8886 | NTTP->removeDefaultArgument(); |
8887 | } |
8888 | } else { |
8889 | TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param); |
8890 | if (TTP->hasDefaultArgument()) { |
8891 | Diag(TTP->getDefaultArgument().getLocation(), |
8892 | diag::err_default_arg_in_partial_spec) |
8893 | << TTP->getDefaultArgument().getSourceRange(); |
8894 | TTP->removeDefaultArgument(); |
8895 | } |
8896 | } |
8897 | } |
8898 | } else if (TemplateParams) { |
8899 | if (TUK == TUK_Friend) |
8900 | Diag(KWLoc, diag::err_template_spec_friend) |
8901 | << FixItHint::CreateRemoval( |
8902 | SourceRange(TemplateParams->getTemplateLoc(), |
8903 | TemplateParams->getRAngleLoc())) |
8904 | << SourceRange(LAngleLoc, RAngleLoc); |
8905 | } else { |
8906 | assert(TUK == TUK_Friend && "should have a 'template<>' for this decl" ); |
8907 | } |
8908 | |
8909 | // Check that the specialization uses the same tag kind as the |
8910 | // original template. |
8911 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec); |
8912 | assert(Kind != TagTypeKind::Enum && |
8913 | "Invalid enum tag in class template spec!" ); |
8914 | if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), |
8915 | NewTag: Kind, isDefinition: TUK == TUK_Definition, NewTagLoc: KWLoc, |
8916 | Name: ClassTemplate->getIdentifier())) { |
8917 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
8918 | << ClassTemplate |
8919 | << FixItHint::CreateReplacement(KWLoc, |
8920 | ClassTemplate->getTemplatedDecl()->getKindName()); |
8921 | Diag(ClassTemplate->getTemplatedDecl()->getLocation(), |
8922 | diag::note_previous_use); |
8923 | Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); |
8924 | } |
8925 | |
8926 | // Translate the parser's template argument list in our AST format. |
8927 | TemplateArgumentListInfo TemplateArgs = |
8928 | makeTemplateArgumentListInfo(S&: *this, TemplateId); |
8929 | |
8930 | // Check for unexpanded parameter packs in any of the template arguments. |
8931 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
8932 | if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I], |
8933 | UPPC: isPartialSpecialization |
8934 | ? UPPC_PartialSpecialization |
8935 | : UPPC_ExplicitSpecialization)) |
8936 | return true; |
8937 | |
8938 | // Check that the template argument list is well-formed for this |
8939 | // template. |
8940 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
8941 | if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, |
8942 | false, SugaredConverted, CanonicalConverted, |
8943 | /*UpdateArgsWithConversions=*/true)) |
8944 | return true; |
8945 | |
8946 | // Find the class template (partial) specialization declaration that |
8947 | // corresponds to these arguments. |
8948 | if (isPartialSpecialization) { |
8949 | if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate, |
8950 | TemplateArgs.size(), |
8951 | CanonicalConverted)) |
8952 | return true; |
8953 | |
8954 | // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we |
8955 | // also do it during instantiation. |
8956 | if (!Name.isDependent() && |
8957 | !TemplateSpecializationType::anyDependentTemplateArguments( |
8958 | TemplateArgs, Converted: CanonicalConverted)) { |
8959 | Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) |
8960 | << ClassTemplate->getDeclName(); |
8961 | isPartialSpecialization = false; |
8962 | } |
8963 | } |
8964 | |
8965 | void *InsertPos = nullptr; |
8966 | ClassTemplateSpecializationDecl *PrevDecl = nullptr; |
8967 | |
8968 | if (isPartialSpecialization) |
8969 | PrevDecl = ClassTemplate->findPartialSpecialization( |
8970 | Args: CanonicalConverted, TPL: TemplateParams, InsertPos); |
8971 | else |
8972 | PrevDecl = ClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
8973 | |
8974 | ClassTemplateSpecializationDecl *Specialization = nullptr; |
8975 | |
8976 | // Check whether we can declare a class template specialization in |
8977 | // the current scope. |
8978 | if (TUK != TUK_Friend && |
8979 | CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, |
8980 | TemplateNameLoc, |
8981 | isPartialSpecialization)) |
8982 | return true; |
8983 | |
8984 | // The canonical type |
8985 | QualType CanonType; |
8986 | if (isPartialSpecialization) { |
8987 | // Build the canonical type that describes the converted template |
8988 | // arguments of the class template partial specialization. |
8989 | TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); |
8990 | CanonType = Context.getTemplateSpecializationType(T: CanonTemplate, |
8991 | Args: CanonicalConverted); |
8992 | |
8993 | if (Context.hasSameType(T1: CanonType, |
8994 | T2: ClassTemplate->getInjectedClassNameSpecialization()) && |
8995 | (!Context.getLangOpts().CPlusPlus20 || |
8996 | !TemplateParams->hasAssociatedConstraints())) { |
8997 | // C++ [temp.class.spec]p9b3: |
8998 | // |
8999 | // -- The argument list of the specialization shall not be identical |
9000 | // to the implicit argument list of the primary template. |
9001 | // |
9002 | // This rule has since been removed, because it's redundant given DR1495, |
9003 | // but we keep it because it produces better diagnostics and recovery. |
9004 | Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) |
9005 | << /*class template*/0 << (TUK == TUK_Definition) |
9006 | << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); |
9007 | return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, |
9008 | Name: ClassTemplate->getIdentifier(), |
9009 | NameLoc: TemplateNameLoc, |
9010 | Attr, |
9011 | TemplateParams, |
9012 | AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(), |
9013 | /*FriendLoc*/SourceLocation(), |
9014 | NumOuterTemplateParamLists: TemplateParameterLists.size() - 1, |
9015 | OuterTemplateParamLists: TemplateParameterLists.data()); |
9016 | } |
9017 | |
9018 | // Create a new class template partial specialization declaration node. |
9019 | ClassTemplatePartialSpecializationDecl *PrevPartial |
9020 | = cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl); |
9021 | ClassTemplatePartialSpecializationDecl *Partial = |
9022 | ClassTemplatePartialSpecializationDecl::Create( |
9023 | Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, |
9024 | IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, |
9025 | ArgInfos: TemplateArgs, CanonInjectedType: CanonType, PrevDecl: PrevPartial); |
9026 | SetNestedNameSpecifier(*this, Partial, SS); |
9027 | if (TemplateParameterLists.size() > 1 && SS.isSet()) { |
9028 | Partial->setTemplateParameterListsInfo( |
9029 | Context, TemplateParameterLists.drop_back(N: 1)); |
9030 | } |
9031 | |
9032 | if (!PrevPartial) |
9033 | ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos); |
9034 | Specialization = Partial; |
9035 | |
9036 | // If we are providing an explicit specialization of a member class |
9037 | // template specialization, make a note of that. |
9038 | if (PrevPartial && PrevPartial->getInstantiatedFromMember()) |
9039 | PrevPartial->setMemberSpecialization(); |
9040 | |
9041 | CheckTemplatePartialSpecialization(Partial); |
9042 | } else { |
9043 | // Create a new class template specialization declaration node for |
9044 | // this explicit specialization or friend declaration. |
9045 | Specialization = ClassTemplateSpecializationDecl::Create( |
9046 | Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc, |
9047 | SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, PrevDecl); |
9048 | SetNestedNameSpecifier(*this, Specialization, SS); |
9049 | if (TemplateParameterLists.size() > 0) { |
9050 | Specialization->setTemplateParameterListsInfo(Context, |
9051 | TemplateParameterLists); |
9052 | } |
9053 | |
9054 | if (!PrevDecl) |
9055 | ClassTemplate->AddSpecialization(D: Specialization, InsertPos); |
9056 | |
9057 | if (CurContext->isDependentContext()) { |
9058 | TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); |
9059 | CanonType = Context.getTemplateSpecializationType(T: CanonTemplate, |
9060 | Args: CanonicalConverted); |
9061 | } else { |
9062 | CanonType = Context.getTypeDeclType(Specialization); |
9063 | } |
9064 | } |
9065 | |
9066 | // C++ [temp.expl.spec]p6: |
9067 | // If a template, a member template or the member of a class template is |
9068 | // explicitly specialized then that specialization shall be declared |
9069 | // before the first use of that specialization that would cause an implicit |
9070 | // instantiation to take place, in every translation unit in which such a |
9071 | // use occurs; no diagnostic is required. |
9072 | if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { |
9073 | bool Okay = false; |
9074 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
9075 | // Is there any previous explicit specialization declaration? |
9076 | if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) { |
9077 | Okay = true; |
9078 | break; |
9079 | } |
9080 | } |
9081 | |
9082 | if (!Okay) { |
9083 | SourceRange Range(TemplateNameLoc, RAngleLoc); |
9084 | Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) |
9085 | << Context.getTypeDeclType(Specialization) << Range; |
9086 | |
9087 | Diag(PrevDecl->getPointOfInstantiation(), |
9088 | diag::note_instantiation_required_here) |
9089 | << (PrevDecl->getTemplateSpecializationKind() |
9090 | != TSK_ImplicitInstantiation); |
9091 | return true; |
9092 | } |
9093 | } |
9094 | |
9095 | // If this is not a friend, note that this is an explicit specialization. |
9096 | if (TUK != TUK_Friend) |
9097 | Specialization->setSpecializationKind(TSK_ExplicitSpecialization); |
9098 | |
9099 | // Check that this isn't a redefinition of this specialization. |
9100 | if (TUK == TUK_Definition) { |
9101 | RecordDecl *Def = Specialization->getDefinition(); |
9102 | NamedDecl *Hidden = nullptr; |
9103 | if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) { |
9104 | SkipBody->ShouldSkip = true; |
9105 | SkipBody->Previous = Def; |
9106 | makeMergedDefinitionVisible(ND: Hidden); |
9107 | } else if (Def) { |
9108 | SourceRange Range(TemplateNameLoc, RAngleLoc); |
9109 | Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range; |
9110 | Diag(Def->getLocation(), diag::note_previous_definition); |
9111 | Specialization->setInvalidDecl(); |
9112 | return true; |
9113 | } |
9114 | } |
9115 | |
9116 | ProcessDeclAttributeList(S, Specialization, Attr); |
9117 | |
9118 | // Add alignment attributes if necessary; these attributes are checked when |
9119 | // the ASTContext lays out the structure. |
9120 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
9121 | AddAlignmentAttributesForRecord(Specialization); |
9122 | AddMsStructLayoutForRecord(Specialization); |
9123 | } |
9124 | |
9125 | if (ModulePrivateLoc.isValid()) |
9126 | Diag(Specialization->getLocation(), diag::err_module_private_specialization) |
9127 | << (isPartialSpecialization? 1 : 0) |
9128 | << FixItHint::CreateRemoval(ModulePrivateLoc); |
9129 | |
9130 | // Build the fully-sugared type for this class template |
9131 | // specialization as the user wrote in the specialization |
9132 | // itself. This means that we'll pretty-print the type retrieved |
9133 | // from the specialization's declaration the way that the user |
9134 | // actually wrote the specialization, rather than formatting the |
9135 | // name based on the "canonical" representation used to store the |
9136 | // template arguments in the specialization. |
9137 | TypeSourceInfo *WrittenTy |
9138 | = Context.getTemplateSpecializationTypeInfo(T: Name, TLoc: TemplateNameLoc, |
9139 | Args: TemplateArgs, Canon: CanonType); |
9140 | if (TUK != TUK_Friend) { |
9141 | Specialization->setTypeAsWritten(WrittenTy); |
9142 | Specialization->setTemplateKeywordLoc(TemplateKWLoc); |
9143 | } |
9144 | |
9145 | // C++ [temp.expl.spec]p9: |
9146 | // A template explicit specialization is in the scope of the |
9147 | // namespace in which the template was defined. |
9148 | // |
9149 | // We actually implement this paragraph where we set the semantic |
9150 | // context (in the creation of the ClassTemplateSpecializationDecl), |
9151 | // but we also maintain the lexical context where the actual |
9152 | // definition occurs. |
9153 | Specialization->setLexicalDeclContext(CurContext); |
9154 | |
9155 | // We may be starting the definition of this specialization. |
9156 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) |
9157 | Specialization->startDefinition(); |
9158 | |
9159 | if (TUK == TUK_Friend) { |
9160 | FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, |
9161 | L: TemplateNameLoc, |
9162 | Friend_: WrittenTy, |
9163 | /*FIXME:*/FriendL: KWLoc); |
9164 | Friend->setAccess(AS_public); |
9165 | CurContext->addDecl(Friend); |
9166 | } else { |
9167 | // Add the specialization into its lexical context, so that it can |
9168 | // be seen when iterating through the list of declarations in that |
9169 | // context. However, specializations are not found by name lookup. |
9170 | CurContext->addDecl(Specialization); |
9171 | } |
9172 | |
9173 | if (SkipBody && SkipBody->ShouldSkip) |
9174 | return SkipBody->Previous; |
9175 | |
9176 | return Specialization; |
9177 | } |
9178 | |
9179 | Decl *Sema::ActOnTemplateDeclarator(Scope *S, |
9180 | MultiTemplateParamsArg TemplateParameterLists, |
9181 | Declarator &D) { |
9182 | Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists); |
9183 | ActOnDocumentableDecl(D: NewDecl); |
9184 | return NewDecl; |
9185 | } |
9186 | |
9187 | Decl *Sema::ActOnConceptDefinition(Scope *S, |
9188 | MultiTemplateParamsArg TemplateParameterLists, |
9189 | IdentifierInfo *Name, SourceLocation NameLoc, |
9190 | Expr *ConstraintExpr) { |
9191 | DeclContext *DC = CurContext; |
9192 | |
9193 | if (!DC->getRedeclContext()->isFileContext()) { |
9194 | Diag(NameLoc, |
9195 | diag::err_concept_decls_may_only_appear_in_global_namespace_scope); |
9196 | return nullptr; |
9197 | } |
9198 | |
9199 | if (TemplateParameterLists.size() > 1) { |
9200 | Diag(NameLoc, diag::err_concept_extra_headers); |
9201 | return nullptr; |
9202 | } |
9203 | |
9204 | TemplateParameterList *Params = TemplateParameterLists.front(); |
9205 | |
9206 | if (Params->size() == 0) { |
9207 | Diag(NameLoc, diag::err_concept_no_parameters); |
9208 | return nullptr; |
9209 | } |
9210 | |
9211 | // Ensure that the parameter pack, if present, is the last parameter in the |
9212 | // template. |
9213 | for (TemplateParameterList::const_iterator ParamIt = Params->begin(), |
9214 | ParamEnd = Params->end(); |
9215 | ParamIt != ParamEnd; ++ParamIt) { |
9216 | Decl const *Param = *ParamIt; |
9217 | if (Param->isParameterPack()) { |
9218 | if (++ParamIt == ParamEnd) |
9219 | break; |
9220 | Diag(Param->getLocation(), |
9221 | diag::err_template_param_pack_must_be_last_template_parameter); |
9222 | return nullptr; |
9223 | } |
9224 | } |
9225 | |
9226 | if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) |
9227 | return nullptr; |
9228 | |
9229 | ConceptDecl *NewDecl = |
9230 | ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params, ConstraintExpr); |
9231 | |
9232 | if (NewDecl->hasAssociatedConstraints()) { |
9233 | // C++2a [temp.concept]p4: |
9234 | // A concept shall not have associated constraints. |
9235 | Diag(NameLoc, diag::err_concept_no_associated_constraints); |
9236 | NewDecl->setInvalidDecl(); |
9237 | } |
9238 | |
9239 | // Check for conflicting previous declaration. |
9240 | DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc); |
9241 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
9242 | forRedeclarationInCurContext()); |
9243 | LookupName(R&: Previous, S); |
9244 | FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage=*/false, |
9245 | /*AllowInlineNamespace*/false); |
9246 | bool AddToScope = true; |
9247 | CheckConceptRedefinition(NewDecl, Previous, AddToScope); |
9248 | |
9249 | ActOnDocumentableDecl(NewDecl); |
9250 | if (AddToScope) |
9251 | PushOnScopeChains(NewDecl, S); |
9252 | return NewDecl; |
9253 | } |
9254 | |
9255 | void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl, |
9256 | LookupResult &Previous, bool &AddToScope) { |
9257 | AddToScope = true; |
9258 | |
9259 | if (Previous.empty()) |
9260 | return; |
9261 | |
9262 | auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl()); |
9263 | if (!OldConcept) { |
9264 | auto *Old = Previous.getRepresentativeDecl(); |
9265 | Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind) |
9266 | << NewDecl->getDeclName(); |
9267 | notePreviousDefinition(Old, New: NewDecl->getLocation()); |
9268 | AddToScope = false; |
9269 | return; |
9270 | } |
9271 | // Check if we can merge with a concept declaration. |
9272 | bool IsSame = Context.isSameEntity(NewDecl, OldConcept); |
9273 | if (!IsSame) { |
9274 | Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept) |
9275 | << NewDecl->getDeclName(); |
9276 | notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation()); |
9277 | AddToScope = false; |
9278 | return; |
9279 | } |
9280 | if (hasReachableDefinition(OldConcept) && |
9281 | IsRedefinitionInModule(NewDecl, OldConcept)) { |
9282 | Diag(NewDecl->getLocation(), diag::err_redefinition) |
9283 | << NewDecl->getDeclName(); |
9284 | notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation()); |
9285 | AddToScope = false; |
9286 | return; |
9287 | } |
9288 | if (!Previous.isSingleResult()) { |
9289 | // FIXME: we should produce an error in case of ambig and failed lookups. |
9290 | // Other decls (e.g. namespaces) also have this shortcoming. |
9291 | return; |
9292 | } |
9293 | // We unwrap canonical decl late to check for module visibility. |
9294 | Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl()); |
9295 | } |
9296 | |
9297 | /// \brief Strips various properties off an implicit instantiation |
9298 | /// that has just been explicitly specialized. |
9299 | static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) { |
9300 | if (MinGW || (isa<FunctionDecl>(D) && |
9301 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) |
9302 | D->dropAttrs<DLLImportAttr, DLLExportAttr>(); |
9303 | |
9304 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) |
9305 | FD->setInlineSpecified(false); |
9306 | } |
9307 | |
9308 | /// Compute the diagnostic location for an explicit instantiation |
9309 | // declaration or definition. |
9310 | static SourceLocation DiagLocForExplicitInstantiation( |
9311 | NamedDecl* D, SourceLocation PointOfInstantiation) { |
9312 | // Explicit instantiations following a specialization have no effect and |
9313 | // hence no PointOfInstantiation. In that case, walk decl backwards |
9314 | // until a valid name loc is found. |
9315 | SourceLocation PrevDiagLoc = PointOfInstantiation; |
9316 | for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid(); |
9317 | Prev = Prev->getPreviousDecl()) { |
9318 | PrevDiagLoc = Prev->getLocation(); |
9319 | } |
9320 | assert(PrevDiagLoc.isValid() && |
9321 | "Explicit instantiation without point of instantiation?" ); |
9322 | return PrevDiagLoc; |
9323 | } |
9324 | |
9325 | /// Diagnose cases where we have an explicit template specialization |
9326 | /// before/after an explicit template instantiation, producing diagnostics |
9327 | /// for those cases where they are required and determining whether the |
9328 | /// new specialization/instantiation will have any effect. |
9329 | /// |
9330 | /// \param NewLoc the location of the new explicit specialization or |
9331 | /// instantiation. |
9332 | /// |
9333 | /// \param NewTSK the kind of the new explicit specialization or instantiation. |
9334 | /// |
9335 | /// \param PrevDecl the previous declaration of the entity. |
9336 | /// |
9337 | /// \param PrevTSK the kind of the old explicit specialization or instantiatin. |
9338 | /// |
9339 | /// \param PrevPointOfInstantiation if valid, indicates where the previous |
9340 | /// declaration was instantiated (either implicitly or explicitly). |
9341 | /// |
9342 | /// \param HasNoEffect will be set to true to indicate that the new |
9343 | /// specialization or instantiation has no effect and should be ignored. |
9344 | /// |
9345 | /// \returns true if there was an error that should prevent the introduction of |
9346 | /// the new declaration into the AST, false otherwise. |
9347 | bool |
9348 | Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, |
9349 | TemplateSpecializationKind NewTSK, |
9350 | NamedDecl *PrevDecl, |
9351 | TemplateSpecializationKind PrevTSK, |
9352 | SourceLocation PrevPointOfInstantiation, |
9353 | bool &HasNoEffect) { |
9354 | HasNoEffect = false; |
9355 | |
9356 | switch (NewTSK) { |
9357 | case TSK_Undeclared: |
9358 | case TSK_ImplicitInstantiation: |
9359 | assert( |
9360 | (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && |
9361 | "previous declaration must be implicit!" ); |
9362 | return false; |
9363 | |
9364 | case TSK_ExplicitSpecialization: |
9365 | switch (PrevTSK) { |
9366 | case TSK_Undeclared: |
9367 | case TSK_ExplicitSpecialization: |
9368 | // Okay, we're just specializing something that is either already |
9369 | // explicitly specialized or has merely been mentioned without any |
9370 | // instantiation. |
9371 | return false; |
9372 | |
9373 | case TSK_ImplicitInstantiation: |
9374 | if (PrevPointOfInstantiation.isInvalid()) { |
9375 | // The declaration itself has not actually been instantiated, so it is |
9376 | // still okay to specialize it. |
9377 | StripImplicitInstantiation( |
9378 | D: PrevDecl, |
9379 | MinGW: Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()); |
9380 | return false; |
9381 | } |
9382 | // Fall through |
9383 | [[fallthrough]]; |
9384 | |
9385 | case TSK_ExplicitInstantiationDeclaration: |
9386 | case TSK_ExplicitInstantiationDefinition: |
9387 | assert((PrevTSK == TSK_ImplicitInstantiation || |
9388 | PrevPointOfInstantiation.isValid()) && |
9389 | "Explicit instantiation without point of instantiation?" ); |
9390 | |
9391 | // C++ [temp.expl.spec]p6: |
9392 | // If a template, a member template or the member of a class template |
9393 | // is explicitly specialized then that specialization shall be declared |
9394 | // before the first use of that specialization that would cause an |
9395 | // implicit instantiation to take place, in every translation unit in |
9396 | // which such a use occurs; no diagnostic is required. |
9397 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
9398 | // Is there any previous explicit specialization declaration? |
9399 | if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) |
9400 | return false; |
9401 | } |
9402 | |
9403 | Diag(NewLoc, diag::err_specialization_after_instantiation) |
9404 | << PrevDecl; |
9405 | Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) |
9406 | << (PrevTSK != TSK_ImplicitInstantiation); |
9407 | |
9408 | return true; |
9409 | } |
9410 | llvm_unreachable("The switch over PrevTSK must be exhaustive." ); |
9411 | |
9412 | case TSK_ExplicitInstantiationDeclaration: |
9413 | switch (PrevTSK) { |
9414 | case TSK_ExplicitInstantiationDeclaration: |
9415 | // This explicit instantiation declaration is redundant (that's okay). |
9416 | HasNoEffect = true; |
9417 | return false; |
9418 | |
9419 | case TSK_Undeclared: |
9420 | case TSK_ImplicitInstantiation: |
9421 | // We're explicitly instantiating something that may have already been |
9422 | // implicitly instantiated; that's fine. |
9423 | return false; |
9424 | |
9425 | case TSK_ExplicitSpecialization: |
9426 | // C++0x [temp.explicit]p4: |
9427 | // For a given set of template parameters, if an explicit instantiation |
9428 | // of a template appears after a declaration of an explicit |
9429 | // specialization for that template, the explicit instantiation has no |
9430 | // effect. |
9431 | HasNoEffect = true; |
9432 | return false; |
9433 | |
9434 | case TSK_ExplicitInstantiationDefinition: |
9435 | // C++0x [temp.explicit]p10: |
9436 | // If an entity is the subject of both an explicit instantiation |
9437 | // declaration and an explicit instantiation definition in the same |
9438 | // translation unit, the definition shall follow the declaration. |
9439 | Diag(NewLoc, |
9440 | diag::err_explicit_instantiation_declaration_after_definition); |
9441 | |
9442 | // Explicit instantiations following a specialization have no effect and |
9443 | // hence no PrevPointOfInstantiation. In that case, walk decl backwards |
9444 | // until a valid name loc is found. |
9445 | Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), |
9446 | diag::note_explicit_instantiation_definition_here); |
9447 | HasNoEffect = true; |
9448 | return false; |
9449 | } |
9450 | llvm_unreachable("Unexpected TemplateSpecializationKind!" ); |
9451 | |
9452 | case TSK_ExplicitInstantiationDefinition: |
9453 | switch (PrevTSK) { |
9454 | case TSK_Undeclared: |
9455 | case TSK_ImplicitInstantiation: |
9456 | // We're explicitly instantiating something that may have already been |
9457 | // implicitly instantiated; that's fine. |
9458 | return false; |
9459 | |
9460 | case TSK_ExplicitSpecialization: |
9461 | // C++ DR 259, C++0x [temp.explicit]p4: |
9462 | // For a given set of template parameters, if an explicit |
9463 | // instantiation of a template appears after a declaration of |
9464 | // an explicit specialization for that template, the explicit |
9465 | // instantiation has no effect. |
9466 | Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization) |
9467 | << PrevDecl; |
9468 | Diag(PrevDecl->getLocation(), |
9469 | diag::note_previous_template_specialization); |
9470 | HasNoEffect = true; |
9471 | return false; |
9472 | |
9473 | case TSK_ExplicitInstantiationDeclaration: |
9474 | // We're explicitly instantiating a definition for something for which we |
9475 | // were previously asked to suppress instantiations. That's fine. |
9476 | |
9477 | // C++0x [temp.explicit]p4: |
9478 | // For a given set of template parameters, if an explicit instantiation |
9479 | // of a template appears after a declaration of an explicit |
9480 | // specialization for that template, the explicit instantiation has no |
9481 | // effect. |
9482 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
9483 | // Is there any previous explicit specialization declaration? |
9484 | if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) { |
9485 | HasNoEffect = true; |
9486 | break; |
9487 | } |
9488 | } |
9489 | |
9490 | return false; |
9491 | |
9492 | case TSK_ExplicitInstantiationDefinition: |
9493 | // C++0x [temp.spec]p5: |
9494 | // For a given template and a given set of template-arguments, |
9495 | // - an explicit instantiation definition shall appear at most once |
9496 | // in a program, |
9497 | |
9498 | // MSVCCompat: MSVC silently ignores duplicate explicit instantiations. |
9499 | Diag(NewLoc, (getLangOpts().MSVCCompat) |
9500 | ? diag::ext_explicit_instantiation_duplicate |
9501 | : diag::err_explicit_instantiation_duplicate) |
9502 | << PrevDecl; |
9503 | Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), |
9504 | diag::note_previous_explicit_instantiation); |
9505 | HasNoEffect = true; |
9506 | return false; |
9507 | } |
9508 | } |
9509 | |
9510 | llvm_unreachable("Missing specialization/instantiation case?" ); |
9511 | } |
9512 | |
9513 | /// Perform semantic analysis for the given dependent function |
9514 | /// template specialization. |
9515 | /// |
9516 | /// The only possible way to get a dependent function template specialization |
9517 | /// is with a friend declaration, like so: |
9518 | /// |
9519 | /// \code |
9520 | /// template \<class T> void foo(T); |
9521 | /// template \<class T> class A { |
9522 | /// friend void foo<>(T); |
9523 | /// }; |
9524 | /// \endcode |
9525 | /// |
9526 | /// There really isn't any useful analysis we can do here, so we |
9527 | /// just store the information. |
9528 | bool Sema::CheckDependentFunctionTemplateSpecialization( |
9529 | FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, |
9530 | LookupResult &Previous) { |
9531 | // Remove anything from Previous that isn't a function template in |
9532 | // the correct context. |
9533 | DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); |
9534 | LookupResult::Filter F = Previous.makeFilter(); |
9535 | enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing }; |
9536 | SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates; |
9537 | while (F.hasNext()) { |
9538 | NamedDecl *D = F.next()->getUnderlyingDecl(); |
9539 | if (!isa<FunctionTemplateDecl>(Val: D)) { |
9540 | F.erase(); |
9541 | DiscardedCandidates.push_back(std::make_pair(x: NotAFunctionTemplate, y&: D)); |
9542 | continue; |
9543 | } |
9544 | |
9545 | if (!FDLookupContext->InEnclosingNamespaceSetOf( |
9546 | NS: D->getDeclContext()->getRedeclContext())) { |
9547 | F.erase(); |
9548 | DiscardedCandidates.push_back(std::make_pair(x: NotAMemberOfEnclosing, y&: D)); |
9549 | continue; |
9550 | } |
9551 | } |
9552 | F.done(); |
9553 | |
9554 | bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None; |
9555 | if (Previous.empty()) { |
9556 | Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match) |
9557 | << IsFriend; |
9558 | for (auto &P : DiscardedCandidates) |
9559 | Diag(P.second->getLocation(), |
9560 | diag::note_dependent_function_template_spec_discard_reason) |
9561 | << P.first << IsFriend; |
9562 | return true; |
9563 | } |
9564 | |
9565 | FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(), |
9566 | TemplateArgs: ExplicitTemplateArgs); |
9567 | return false; |
9568 | } |
9569 | |
9570 | /// Perform semantic analysis for the given function template |
9571 | /// specialization. |
9572 | /// |
9573 | /// This routine performs all of the semantic analysis required for an |
9574 | /// explicit function template specialization. On successful completion, |
9575 | /// the function declaration \p FD will become a function template |
9576 | /// specialization. |
9577 | /// |
9578 | /// \param FD the function declaration, which will be updated to become a |
9579 | /// function template specialization. |
9580 | /// |
9581 | /// \param ExplicitTemplateArgs the explicitly-provided template arguments, |
9582 | /// if any. Note that this may be valid info even when 0 arguments are |
9583 | /// explicitly provided as in, e.g., \c void sort<>(char*, char*); |
9584 | /// as it anyway contains info on the angle brackets locations. |
9585 | /// |
9586 | /// \param Previous the set of declarations that may be specialized by |
9587 | /// this function specialization. |
9588 | /// |
9589 | /// \param QualifiedFriend whether this is a lookup for a qualified friend |
9590 | /// declaration with no explicit template argument list that might be |
9591 | /// befriending a function template specialization. |
9592 | bool Sema::CheckFunctionTemplateSpecialization( |
9593 | FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, |
9594 | LookupResult &Previous, bool QualifiedFriend) { |
9595 | // The set of function template specializations that could match this |
9596 | // explicit function template specialization. |
9597 | UnresolvedSet<8> Candidates; |
9598 | TemplateSpecCandidateSet FailedCandidates(FD->getLocation(), |
9599 | /*ForTakingAddress=*/false); |
9600 | |
9601 | llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8> |
9602 | ConvertedTemplateArgs; |
9603 | |
9604 | DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); |
9605 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
9606 | I != E; ++I) { |
9607 | NamedDecl *Ovl = (*I)->getUnderlyingDecl(); |
9608 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) { |
9609 | // Only consider templates found within the same semantic lookup scope as |
9610 | // FD. |
9611 | if (!FDLookupContext->InEnclosingNamespaceSetOf( |
9612 | NS: Ovl->getDeclContext()->getRedeclContext())) |
9613 | continue; |
9614 | |
9615 | // When matching a constexpr member function template specialization |
9616 | // against the primary template, we don't yet know whether the |
9617 | // specialization has an implicit 'const' (because we don't know whether |
9618 | // it will be a static member function until we know which template it |
9619 | // specializes), so adjust it now assuming it specializes this template. |
9620 | QualType FT = FD->getType(); |
9621 | if (FD->isConstexpr()) { |
9622 | CXXMethodDecl *OldMD = |
9623 | dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl()); |
9624 | if (OldMD && OldMD->isConst()) { |
9625 | const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>(); |
9626 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
9627 | EPI.TypeQuals.addConst(); |
9628 | FT = Context.getFunctionType(ResultTy: FPT->getReturnType(), |
9629 | Args: FPT->getParamTypes(), EPI); |
9630 | } |
9631 | } |
9632 | |
9633 | TemplateArgumentListInfo Args; |
9634 | if (ExplicitTemplateArgs) |
9635 | Args = *ExplicitTemplateArgs; |
9636 | |
9637 | // C++ [temp.expl.spec]p11: |
9638 | // A trailing template-argument can be left unspecified in the |
9639 | // template-id naming an explicit function template specialization |
9640 | // provided it can be deduced from the function argument type. |
9641 | // Perform template argument deduction to determine whether we may be |
9642 | // specializing this template. |
9643 | // FIXME: It is somewhat wasteful to build |
9644 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
9645 | FunctionDecl *Specialization = nullptr; |
9646 | if (TemplateDeductionResult TDK = DeduceTemplateArguments( |
9647 | cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()), |
9648 | ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info); |
9649 | TDK != TemplateDeductionResult::Success) { |
9650 | // Template argument deduction failed; record why it failed, so |
9651 | // that we can provide nifty diagnostics. |
9652 | FailedCandidates.addCandidate().set( |
9653 | I.getPair(), FunTmpl->getTemplatedDecl(), |
9654 | MakeDeductionFailureInfo(Context, TDK, Info)); |
9655 | (void)TDK; |
9656 | continue; |
9657 | } |
9658 | |
9659 | // Target attributes are part of the cuda function signature, so |
9660 | // the deduced template's cuda target must match that of the |
9661 | // specialization. Given that C++ template deduction does not |
9662 | // take target attributes into account, we reject candidates |
9663 | // here that have a different target. |
9664 | if (LangOpts.CUDA && |
9665 | IdentifyCUDATarget(D: Specialization, |
9666 | /* IgnoreImplicitHDAttr = */ true) != |
9667 | IdentifyCUDATarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) { |
9668 | FailedCandidates.addCandidate().set( |
9669 | I.getPair(), FunTmpl->getTemplatedDecl(), |
9670 | MakeDeductionFailureInfo( |
9671 | Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info)); |
9672 | continue; |
9673 | } |
9674 | |
9675 | // Record this candidate. |
9676 | if (ExplicitTemplateArgs) |
9677 | ConvertedTemplateArgs[Specialization] = std::move(Args); |
9678 | Candidates.addDecl(Specialization, I.getAccess()); |
9679 | } |
9680 | } |
9681 | |
9682 | // For a qualified friend declaration (with no explicit marker to indicate |
9683 | // that a template specialization was intended), note all (template and |
9684 | // non-template) candidates. |
9685 | if (QualifiedFriend && Candidates.empty()) { |
9686 | Diag(FD->getLocation(), diag::err_qualified_friend_no_match) |
9687 | << FD->getDeclName() << FDLookupContext; |
9688 | // FIXME: We should form a single candidate list and diagnose all |
9689 | // candidates at once, to get proper sorting and limiting. |
9690 | for (auto *OldND : Previous) { |
9691 | if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl())) |
9692 | NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false); |
9693 | } |
9694 | FailedCandidates.NoteCandidates(*this, FD->getLocation()); |
9695 | return true; |
9696 | } |
9697 | |
9698 | // Find the most specialized function template. |
9699 | UnresolvedSetIterator Result = getMostSpecialized( |
9700 | Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(), |
9701 | PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(), |
9702 | PDiag(diag::err_function_template_spec_ambiguous) |
9703 | << FD->getDeclName() << (ExplicitTemplateArgs != nullptr), |
9704 | PDiag(diag::note_function_template_spec_matched)); |
9705 | |
9706 | if (Result == Candidates.end()) |
9707 | return true; |
9708 | |
9709 | // Ignore access information; it doesn't figure into redeclaration checking. |
9710 | FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result); |
9711 | |
9712 | FunctionTemplateSpecializationInfo *SpecInfo |
9713 | = Specialization->getTemplateSpecializationInfo(); |
9714 | assert(SpecInfo && "Function template specialization info missing?" ); |
9715 | |
9716 | // Note: do not overwrite location info if previous template |
9717 | // specialization kind was explicit. |
9718 | TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind(); |
9719 | if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) { |
9720 | Specialization->setLocation(FD->getLocation()); |
9721 | Specialization->setLexicalDeclContext(FD->getLexicalDeclContext()); |
9722 | // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr |
9723 | // function can differ from the template declaration with respect to |
9724 | // the constexpr specifier. |
9725 | // FIXME: We need an update record for this AST mutation. |
9726 | // FIXME: What if there are multiple such prior declarations (for instance, |
9727 | // from different modules)? |
9728 | Specialization->setConstexprKind(FD->getConstexprKind()); |
9729 | } |
9730 | |
9731 | // FIXME: Check if the prior specialization has a point of instantiation. |
9732 | // If so, we have run afoul of . |
9733 | |
9734 | // If this is a friend declaration, then we're not really declaring |
9735 | // an explicit specialization. |
9736 | bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); |
9737 | |
9738 | // Check the scope of this explicit specialization. |
9739 | if (!isFriend && |
9740 | CheckTemplateSpecializationScope(*this, |
9741 | Specialization->getPrimaryTemplate(), |
9742 | Specialization, FD->getLocation(), |
9743 | false)) |
9744 | return true; |
9745 | |
9746 | // C++ [temp.expl.spec]p6: |
9747 | // If a template, a member template or the member of a class template is |
9748 | // explicitly specialized then that specialization shall be declared |
9749 | // before the first use of that specialization that would cause an implicit |
9750 | // instantiation to take place, in every translation unit in which such a |
9751 | // use occurs; no diagnostic is required. |
9752 | bool HasNoEffect = false; |
9753 | if (!isFriend && |
9754 | CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(), |
9755 | NewTSK: TSK_ExplicitSpecialization, |
9756 | PrevDecl: Specialization, |
9757 | PrevTSK: SpecInfo->getTemplateSpecializationKind(), |
9758 | PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(), |
9759 | HasNoEffect)) |
9760 | return true; |
9761 | |
9762 | // Mark the prior declaration as an explicit specialization, so that later |
9763 | // clients know that this is an explicit specialization. |
9764 | if (!isFriend) { |
9765 | // Since explicit specializations do not inherit '=delete' from their |
9766 | // primary function template - check if the 'specialization' that was |
9767 | // implicitly generated (during template argument deduction for partial |
9768 | // ordering) from the most specialized of all the function templates that |
9769 | // 'FD' could have been specializing, has a 'deleted' definition. If so, |
9770 | // first check that it was implicitly generated during template argument |
9771 | // deduction by making sure it wasn't referenced, and then reset the deleted |
9772 | // flag to not-deleted, so that we can inherit that information from 'FD'. |
9773 | if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() && |
9774 | !Specialization->getCanonicalDecl()->isReferenced()) { |
9775 | // FIXME: This assert will not hold in the presence of modules. |
9776 | assert( |
9777 | Specialization->getCanonicalDecl() == Specialization && |
9778 | "This must be the only existing declaration of this specialization" ); |
9779 | // FIXME: We need an update record for this AST mutation. |
9780 | Specialization->setDeletedAsWritten(false); |
9781 | } |
9782 | // FIXME: We need an update record for this AST mutation. |
9783 | SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); |
9784 | MarkUnusedFileScopedDecl(Specialization); |
9785 | } |
9786 | |
9787 | // Turn the given function declaration into a function template |
9788 | // specialization, with the template arguments from the previous |
9789 | // specialization. |
9790 | // Take copies of (semantic and syntactic) template argument lists. |
9791 | const TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy( |
9792 | Context, Args: Specialization->getTemplateSpecializationArgs()->asArray()); |
9793 | FD->setFunctionTemplateSpecialization( |
9794 | Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr, |
9795 | TSK: SpecInfo->getTemplateSpecializationKind(), |
9796 | TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr); |
9797 | |
9798 | // A function template specialization inherits the target attributes |
9799 | // of its template. (We require the attributes explicitly in the |
9800 | // code to match, but a template may have implicit attributes by |
9801 | // virtue e.g. of being constexpr, and it passes these implicit |
9802 | // attributes on to its specializations.) |
9803 | if (LangOpts.CUDA) |
9804 | inheritCUDATargetAttrs(FD, TD: *Specialization->getPrimaryTemplate()); |
9805 | |
9806 | // The "previous declaration" for this function template specialization is |
9807 | // the prior function template specialization. |
9808 | Previous.clear(); |
9809 | Previous.addDecl(Specialization); |
9810 | return false; |
9811 | } |
9812 | |
9813 | /// Perform semantic analysis for the given non-template member |
9814 | /// specialization. |
9815 | /// |
9816 | /// This routine performs all of the semantic analysis required for an |
9817 | /// explicit member function specialization. On successful completion, |
9818 | /// the function declaration \p FD will become a member function |
9819 | /// specialization. |
9820 | /// |
9821 | /// \param Member the member declaration, which will be updated to become a |
9822 | /// specialization. |
9823 | /// |
9824 | /// \param Previous the set of declarations, one of which may be specialized |
9825 | /// by this function specialization; the set will be modified to contain the |
9826 | /// redeclared member. |
9827 | bool |
9828 | Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { |
9829 | assert(!isa<TemplateDecl>(Member) && "Only for non-template members" ); |
9830 | |
9831 | // Try to find the member we are instantiating. |
9832 | NamedDecl *FoundInstantiation = nullptr; |
9833 | NamedDecl *Instantiation = nullptr; |
9834 | NamedDecl *InstantiatedFrom = nullptr; |
9835 | MemberSpecializationInfo *MSInfo = nullptr; |
9836 | |
9837 | if (Previous.empty()) { |
9838 | // Nowhere to look anyway. |
9839 | } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) { |
9840 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
9841 | I != E; ++I) { |
9842 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
9843 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
9844 | QualType Adjusted = Function->getType(); |
9845 | if (!hasExplicitCallingConv(T: Adjusted)) |
9846 | Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType()); |
9847 | // This doesn't handle deduced return types, but both function |
9848 | // declarations should be undeduced at this point. |
9849 | if (Context.hasSameType(Adjusted, Method->getType())) { |
9850 | FoundInstantiation = *I; |
9851 | Instantiation = Method; |
9852 | InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); |
9853 | MSInfo = Method->getMemberSpecializationInfo(); |
9854 | break; |
9855 | } |
9856 | } |
9857 | } |
9858 | } else if (isa<VarDecl>(Val: Member)) { |
9859 | VarDecl *PrevVar; |
9860 | if (Previous.isSingleResult() && |
9861 | (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl()))) |
9862 | if (PrevVar->isStaticDataMember()) { |
9863 | FoundInstantiation = Previous.getRepresentativeDecl(); |
9864 | Instantiation = PrevVar; |
9865 | InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); |
9866 | MSInfo = PrevVar->getMemberSpecializationInfo(); |
9867 | } |
9868 | } else if (isa<RecordDecl>(Val: Member)) { |
9869 | CXXRecordDecl *PrevRecord; |
9870 | if (Previous.isSingleResult() && |
9871 | (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) { |
9872 | FoundInstantiation = Previous.getRepresentativeDecl(); |
9873 | Instantiation = PrevRecord; |
9874 | InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); |
9875 | MSInfo = PrevRecord->getMemberSpecializationInfo(); |
9876 | } |
9877 | } else if (isa<EnumDecl>(Val: Member)) { |
9878 | EnumDecl *PrevEnum; |
9879 | if (Previous.isSingleResult() && |
9880 | (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) { |
9881 | FoundInstantiation = Previous.getRepresentativeDecl(); |
9882 | Instantiation = PrevEnum; |
9883 | InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum(); |
9884 | MSInfo = PrevEnum->getMemberSpecializationInfo(); |
9885 | } |
9886 | } |
9887 | |
9888 | if (!Instantiation) { |
9889 | // There is no previous declaration that matches. Since member |
9890 | // specializations are always out-of-line, the caller will complain about |
9891 | // this mismatch later. |
9892 | return false; |
9893 | } |
9894 | |
9895 | // A member specialization in a friend declaration isn't really declaring |
9896 | // an explicit specialization, just identifying a specific (possibly implicit) |
9897 | // specialization. Don't change the template specialization kind. |
9898 | // |
9899 | // FIXME: Is this really valid? Other compilers reject. |
9900 | if (Member->getFriendObjectKind() != Decl::FOK_None) { |
9901 | // Preserve instantiation information. |
9902 | if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) { |
9903 | cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction( |
9904 | cast<CXXMethodDecl>(Val: InstantiatedFrom), |
9905 | cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind()); |
9906 | } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) { |
9907 | cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass( |
9908 | RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), |
9909 | TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind()); |
9910 | } |
9911 | |
9912 | Previous.clear(); |
9913 | Previous.addDecl(D: FoundInstantiation); |
9914 | return false; |
9915 | } |
9916 | |
9917 | // Make sure that this is a specialization of a member. |
9918 | if (!InstantiatedFrom) { |
9919 | Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) |
9920 | << Member; |
9921 | Diag(Instantiation->getLocation(), diag::note_specialized_decl); |
9922 | return true; |
9923 | } |
9924 | |
9925 | // C++ [temp.expl.spec]p6: |
9926 | // If a template, a member template or the member of a class template is |
9927 | // explicitly specialized then that specialization shall be declared |
9928 | // before the first use of that specialization that would cause an implicit |
9929 | // instantiation to take place, in every translation unit in which such a |
9930 | // use occurs; no diagnostic is required. |
9931 | assert(MSInfo && "Member specialization info missing?" ); |
9932 | |
9933 | bool HasNoEffect = false; |
9934 | if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(), |
9935 | NewTSK: TSK_ExplicitSpecialization, |
9936 | PrevDecl: Instantiation, |
9937 | PrevTSK: MSInfo->getTemplateSpecializationKind(), |
9938 | PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(), |
9939 | HasNoEffect)) |
9940 | return true; |
9941 | |
9942 | // Check the scope of this explicit specialization. |
9943 | if (CheckTemplateSpecializationScope(*this, |
9944 | InstantiatedFrom, |
9945 | Instantiation, Member->getLocation(), |
9946 | false)) |
9947 | return true; |
9948 | |
9949 | // Note that this member specialization is an "instantiation of" the |
9950 | // corresponding member of the original template. |
9951 | if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) { |
9952 | FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation); |
9953 | if (InstantiationFunction->getTemplateSpecializationKind() == |
9954 | TSK_ImplicitInstantiation) { |
9955 | // Explicit specializations of member functions of class templates do not |
9956 | // inherit '=delete' from the member function they are specializing. |
9957 | if (InstantiationFunction->isDeleted()) { |
9958 | // FIXME: This assert will not hold in the presence of modules. |
9959 | assert(InstantiationFunction->getCanonicalDecl() == |
9960 | InstantiationFunction); |
9961 | // FIXME: We need an update record for this AST mutation. |
9962 | InstantiationFunction->setDeletedAsWritten(false); |
9963 | } |
9964 | } |
9965 | |
9966 | MemberFunction->setInstantiationOfMemberFunction( |
9967 | cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK_ExplicitSpecialization); |
9968 | } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) { |
9969 | MemberVar->setInstantiationOfStaticDataMember( |
9970 | VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization); |
9971 | } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) { |
9972 | MemberClass->setInstantiationOfMemberClass( |
9973 | RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization); |
9974 | } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) { |
9975 | MemberEnum->setInstantiationOfMemberEnum( |
9976 | ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization); |
9977 | } else { |
9978 | llvm_unreachable("unknown member specialization kind" ); |
9979 | } |
9980 | |
9981 | // Save the caller the trouble of having to figure out which declaration |
9982 | // this specialization matches. |
9983 | Previous.clear(); |
9984 | Previous.addDecl(D: FoundInstantiation); |
9985 | return false; |
9986 | } |
9987 | |
9988 | /// Complete the explicit specialization of a member of a class template by |
9989 | /// updating the instantiated member to be marked as an explicit specialization. |
9990 | /// |
9991 | /// \param OrigD The member declaration instantiated from the template. |
9992 | /// \param Loc The location of the explicit specialization of the member. |
9993 | template<typename DeclT> |
9994 | static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, |
9995 | SourceLocation Loc) { |
9996 | if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) |
9997 | return; |
9998 | |
9999 | // FIXME: Inform AST mutation listeners of this AST mutation. |
10000 | // FIXME: If there are multiple in-class declarations of the member (from |
10001 | // multiple modules, or a declaration and later definition of a member type), |
10002 | // should we update all of them? |
10003 | OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization); |
10004 | OrigD->setLocation(Loc); |
10005 | } |
10006 | |
10007 | void Sema::CompleteMemberSpecialization(NamedDecl *Member, |
10008 | LookupResult &Previous) { |
10009 | NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl()); |
10010 | if (Instantiation == Member) |
10011 | return; |
10012 | |
10013 | if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation)) |
10014 | completeMemberSpecializationImpl(*this, Function, Member->getLocation()); |
10015 | else if (auto *Var = dyn_cast<VarDecl>(Instantiation)) |
10016 | completeMemberSpecializationImpl(*this, Var, Member->getLocation()); |
10017 | else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation)) |
10018 | completeMemberSpecializationImpl(*this, Record, Member->getLocation()); |
10019 | else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation)) |
10020 | completeMemberSpecializationImpl(*this, Enum, Member->getLocation()); |
10021 | else |
10022 | llvm_unreachable("unknown member specialization kind" ); |
10023 | } |
10024 | |
10025 | /// Check the scope of an explicit instantiation. |
10026 | /// |
10027 | /// \returns true if a serious error occurs, false otherwise. |
10028 | static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, |
10029 | SourceLocation InstLoc, |
10030 | bool WasQualifiedName) { |
10031 | DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); |
10032 | DeclContext *CurContext = S.CurContext->getRedeclContext(); |
10033 | |
10034 | if (CurContext->isRecord()) { |
10035 | S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) |
10036 | << D; |
10037 | return true; |
10038 | } |
10039 | |
10040 | // C++11 [temp.explicit]p3: |
10041 | // An explicit instantiation shall appear in an enclosing namespace of its |
10042 | // template. If the name declared in the explicit instantiation is an |
10043 | // unqualified name, the explicit instantiation shall appear in the |
10044 | // namespace where its template is declared or, if that namespace is inline |
10045 | // (7.3.1), any namespace from its enclosing namespace set. |
10046 | // |
10047 | // This is DR275, which we do not retroactively apply to C++98/03. |
10048 | if (WasQualifiedName) { |
10049 | if (CurContext->Encloses(DC: OrigContext)) |
10050 | return false; |
10051 | } else { |
10052 | if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext)) |
10053 | return false; |
10054 | } |
10055 | |
10056 | if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) { |
10057 | if (WasQualifiedName) |
10058 | S.Diag(InstLoc, |
10059 | S.getLangOpts().CPlusPlus11? |
10060 | diag::err_explicit_instantiation_out_of_scope : |
10061 | diag::warn_explicit_instantiation_out_of_scope_0x) |
10062 | << D << NS; |
10063 | else |
10064 | S.Diag(InstLoc, |
10065 | S.getLangOpts().CPlusPlus11? |
10066 | diag::err_explicit_instantiation_unqualified_wrong_namespace : |
10067 | diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) |
10068 | << D << NS; |
10069 | } else |
10070 | S.Diag(InstLoc, |
10071 | S.getLangOpts().CPlusPlus11? |
10072 | diag::err_explicit_instantiation_must_be_global : |
10073 | diag::warn_explicit_instantiation_must_be_global_0x) |
10074 | << D; |
10075 | S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); |
10076 | return false; |
10077 | } |
10078 | |
10079 | /// Common checks for whether an explicit instantiation of \p D is valid. |
10080 | static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, |
10081 | SourceLocation InstLoc, |
10082 | bool WasQualifiedName, |
10083 | TemplateSpecializationKind TSK) { |
10084 | // C++ [temp.explicit]p13: |
10085 | // An explicit instantiation declaration shall not name a specialization of |
10086 | // a template with internal linkage. |
10087 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
10088 | D->getFormalLinkage() == Linkage::Internal) { |
10089 | S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D; |
10090 | return true; |
10091 | } |
10092 | |
10093 | // C++11 [temp.explicit]p3: [DR 275] |
10094 | // An explicit instantiation shall appear in an enclosing namespace of its |
10095 | // template. |
10096 | if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName)) |
10097 | return true; |
10098 | |
10099 | return false; |
10100 | } |
10101 | |
10102 | /// Determine whether the given scope specifier has a template-id in it. |
10103 | static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { |
10104 | if (!SS.isSet()) |
10105 | return false; |
10106 | |
10107 | // C++11 [temp.explicit]p3: |
10108 | // If the explicit instantiation is for a member function, a member class |
10109 | // or a static data member of a class template specialization, the name of |
10110 | // the class template specialization in the qualified-id for the member |
10111 | // name shall be a simple-template-id. |
10112 | // |
10113 | // C++98 has the same restriction, just worded differently. |
10114 | for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS; |
10115 | NNS = NNS->getPrefix()) |
10116 | if (const Type *T = NNS->getAsType()) |
10117 | if (isa<TemplateSpecializationType>(Val: T)) |
10118 | return true; |
10119 | |
10120 | return false; |
10121 | } |
10122 | |
10123 | /// Make a dllexport or dllimport attr on a class template specialization take |
10124 | /// effect. |
10125 | static void dllExportImportClassTemplateSpecialization( |
10126 | Sema &S, ClassTemplateSpecializationDecl *Def) { |
10127 | auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(Def)); |
10128 | assert(A && "dllExportImportClassTemplateSpecialization called " |
10129 | "on Def without dllexport or dllimport" ); |
10130 | |
10131 | // We reject explicit instantiations in class scope, so there should |
10132 | // never be any delayed exported classes to worry about. |
10133 | assert(S.DelayedDllExportClasses.empty() && |
10134 | "delayed exports present at explicit instantiation" ); |
10135 | S.checkClassLevelDLLAttribute(Def); |
10136 | |
10137 | // Propagate attribute to base class templates. |
10138 | for (auto &B : Def->bases()) { |
10139 | if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>( |
10140 | B.getType()->getAsCXXRecordDecl())) |
10141 | S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc()); |
10142 | } |
10143 | |
10144 | S.referenceDLLExportedClassMethods(); |
10145 | } |
10146 | |
10147 | // Explicit instantiation of a class template specialization |
10148 | DeclResult Sema::ActOnExplicitInstantiation( |
10149 | Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, |
10150 | unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, |
10151 | TemplateTy TemplateD, SourceLocation TemplateNameLoc, |
10152 | SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, |
10153 | SourceLocation RAngleLoc, const ParsedAttributesView &Attr) { |
10154 | // Find the class template we're specializing |
10155 | TemplateName Name = TemplateD.get(); |
10156 | TemplateDecl *TD = Name.getAsTemplateDecl(); |
10157 | // Check that the specialization uses the same tag kind as the |
10158 | // original template. |
10159 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec); |
10160 | assert(Kind != TagTypeKind::Enum && |
10161 | "Invalid enum tag in class template explicit instantiation!" ); |
10162 | |
10163 | ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD); |
10164 | |
10165 | if (!ClassTemplate) { |
10166 | NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind); |
10167 | Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) |
10168 | << TD << NTK << llvm::to_underlying(Kind); |
10169 | Diag(TD->getLocation(), diag::note_previous_use); |
10170 | return true; |
10171 | } |
10172 | |
10173 | if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), |
10174 | NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc, |
10175 | Name: ClassTemplate->getIdentifier())) { |
10176 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
10177 | << ClassTemplate |
10178 | << FixItHint::CreateReplacement(KWLoc, |
10179 | ClassTemplate->getTemplatedDecl()->getKindName()); |
10180 | Diag(ClassTemplate->getTemplatedDecl()->getLocation(), |
10181 | diag::note_previous_use); |
10182 | Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); |
10183 | } |
10184 | |
10185 | // C++0x [temp.explicit]p2: |
10186 | // There are two forms of explicit instantiation: an explicit instantiation |
10187 | // definition and an explicit instantiation declaration. An explicit |
10188 | // instantiation declaration begins with the extern keyword. [...] |
10189 | TemplateSpecializationKind TSK = ExternLoc.isInvalid() |
10190 | ? TSK_ExplicitInstantiationDefinition |
10191 | : TSK_ExplicitInstantiationDeclaration; |
10192 | |
10193 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
10194 | !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { |
10195 | // Check for dllexport class template instantiation declarations, |
10196 | // except for MinGW mode. |
10197 | for (const ParsedAttr &AL : Attr) { |
10198 | if (AL.getKind() == ParsedAttr::AT_DLLExport) { |
10199 | Diag(ExternLoc, |
10200 | diag::warn_attribute_dllexport_explicit_instantiation_decl); |
10201 | Diag(AL.getLoc(), diag::note_attribute); |
10202 | break; |
10203 | } |
10204 | } |
10205 | |
10206 | if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) { |
10207 | Diag(ExternLoc, |
10208 | diag::warn_attribute_dllexport_explicit_instantiation_decl); |
10209 | Diag(A->getLocation(), diag::note_attribute); |
10210 | } |
10211 | } |
10212 | |
10213 | // In MSVC mode, dllimported explicit instantiation definitions are treated as |
10214 | // instantiation declarations for most purposes. |
10215 | bool DLLImportExplicitInstantiationDef = false; |
10216 | if (TSK == TSK_ExplicitInstantiationDefinition && |
10217 | Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
10218 | // Check for dllimport class template instantiation definitions. |
10219 | bool DLLImport = |
10220 | ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>(); |
10221 | for (const ParsedAttr &AL : Attr) { |
10222 | if (AL.getKind() == ParsedAttr::AT_DLLImport) |
10223 | DLLImport = true; |
10224 | if (AL.getKind() == ParsedAttr::AT_DLLExport) { |
10225 | // dllexport trumps dllimport here. |
10226 | DLLImport = false; |
10227 | break; |
10228 | } |
10229 | } |
10230 | if (DLLImport) { |
10231 | TSK = TSK_ExplicitInstantiationDeclaration; |
10232 | DLLImportExplicitInstantiationDef = true; |
10233 | } |
10234 | } |
10235 | |
10236 | // Translate the parser's template argument list in our AST format. |
10237 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
10238 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
10239 | |
10240 | // Check that the template argument list is well-formed for this |
10241 | // template. |
10242 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
10243 | if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, |
10244 | false, SugaredConverted, CanonicalConverted, |
10245 | /*UpdateArgsWithConversions=*/true)) |
10246 | return true; |
10247 | |
10248 | // Find the class template specialization declaration that |
10249 | // corresponds to these arguments. |
10250 | void *InsertPos = nullptr; |
10251 | ClassTemplateSpecializationDecl *PrevDecl = |
10252 | ClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
10253 | |
10254 | TemplateSpecializationKind PrevDecl_TSK |
10255 | = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; |
10256 | |
10257 | if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr && |
10258 | Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { |
10259 | // Check for dllexport class template instantiation definitions in MinGW |
10260 | // mode, if a previous declaration of the instantiation was seen. |
10261 | for (const ParsedAttr &AL : Attr) { |
10262 | if (AL.getKind() == ParsedAttr::AT_DLLExport) { |
10263 | Diag(AL.getLoc(), |
10264 | diag::warn_attribute_dllexport_explicit_instantiation_def); |
10265 | break; |
10266 | } |
10267 | } |
10268 | } |
10269 | |
10270 | if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc, |
10271 | SS.isSet(), TSK)) |
10272 | return true; |
10273 | |
10274 | ClassTemplateSpecializationDecl *Specialization = nullptr; |
10275 | |
10276 | bool HasNoEffect = false; |
10277 | if (PrevDecl) { |
10278 | if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, |
10279 | PrevDecl, PrevDecl_TSK, |
10280 | PrevDecl->getPointOfInstantiation(), |
10281 | HasNoEffect)) |
10282 | return PrevDecl; |
10283 | |
10284 | // Even though HasNoEffect == true means that this explicit instantiation |
10285 | // has no effect on semantics, we go on to put its syntax in the AST. |
10286 | |
10287 | if (PrevDecl_TSK == TSK_ImplicitInstantiation || |
10288 | PrevDecl_TSK == TSK_Undeclared) { |
10289 | // Since the only prior class template specialization with these |
10290 | // arguments was referenced but not declared, reuse that |
10291 | // declaration node as our own, updating the source location |
10292 | // for the template name to reflect our new declaration. |
10293 | // (Other source locations will be updated later.) |
10294 | Specialization = PrevDecl; |
10295 | Specialization->setLocation(TemplateNameLoc); |
10296 | PrevDecl = nullptr; |
10297 | } |
10298 | |
10299 | if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && |
10300 | DLLImportExplicitInstantiationDef) { |
10301 | // The new specialization might add a dllimport attribute. |
10302 | HasNoEffect = false; |
10303 | } |
10304 | } |
10305 | |
10306 | if (!Specialization) { |
10307 | // Create a new class template specialization declaration node for |
10308 | // this explicit specialization. |
10309 | Specialization = ClassTemplateSpecializationDecl::Create( |
10310 | Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc, |
10311 | SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, PrevDecl); |
10312 | SetNestedNameSpecifier(*this, Specialization, SS); |
10313 | |
10314 | // A MSInheritanceAttr attached to the previous declaration must be |
10315 | // propagated to the new node prior to instantiation. |
10316 | if (PrevDecl) { |
10317 | if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) { |
10318 | auto *Clone = A->clone(getASTContext()); |
10319 | Clone->setInherited(true); |
10320 | Specialization->addAttr(A: Clone); |
10321 | Consumer.AssignInheritanceModel(Specialization); |
10322 | } |
10323 | } |
10324 | |
10325 | if (!HasNoEffect && !PrevDecl) { |
10326 | // Insert the new specialization. |
10327 | ClassTemplate->AddSpecialization(D: Specialization, InsertPos); |
10328 | } |
10329 | } |
10330 | |
10331 | // Build the fully-sugared type for this explicit instantiation as |
10332 | // the user wrote in the explicit instantiation itself. This means |
10333 | // that we'll pretty-print the type retrieved from the |
10334 | // specialization's declaration the way that the user actually wrote |
10335 | // the explicit instantiation, rather than formatting the name based |
10336 | // on the "canonical" representation used to store the template |
10337 | // arguments in the specialization. |
10338 | TypeSourceInfo *WrittenTy |
10339 | = Context.getTemplateSpecializationTypeInfo(T: Name, TLoc: TemplateNameLoc, |
10340 | Args: TemplateArgs, |
10341 | Canon: Context.getTypeDeclType(Specialization)); |
10342 | Specialization->setTypeAsWritten(WrittenTy); |
10343 | |
10344 | // Set source locations for keywords. |
10345 | Specialization->setExternLoc(ExternLoc); |
10346 | Specialization->setTemplateKeywordLoc(TemplateLoc); |
10347 | Specialization->setBraceRange(SourceRange()); |
10348 | |
10349 | bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>(); |
10350 | ProcessDeclAttributeList(S, Specialization, Attr); |
10351 | |
10352 | // Add the explicit instantiation into its lexical context. However, |
10353 | // since explicit instantiations are never found by name lookup, we |
10354 | // just put it into the declaration context directly. |
10355 | Specialization->setLexicalDeclContext(CurContext); |
10356 | CurContext->addDecl(Specialization); |
10357 | |
10358 | // Syntax is now OK, so return if it has no other effect on semantics. |
10359 | if (HasNoEffect) { |
10360 | // Set the template specialization kind. |
10361 | Specialization->setTemplateSpecializationKind(TSK); |
10362 | return Specialization; |
10363 | } |
10364 | |
10365 | // C++ [temp.explicit]p3: |
10366 | // A definition of a class template or class member template |
10367 | // shall be in scope at the point of the explicit instantiation of |
10368 | // the class template or class member template. |
10369 | // |
10370 | // This check comes when we actually try to perform the |
10371 | // instantiation. |
10372 | ClassTemplateSpecializationDecl *Def |
10373 | = cast_or_null<ClassTemplateSpecializationDecl>( |
10374 | Specialization->getDefinition()); |
10375 | if (!Def) |
10376 | InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK); |
10377 | else if (TSK == TSK_ExplicitInstantiationDefinition) { |
10378 | MarkVTableUsed(TemplateNameLoc, Specialization, true); |
10379 | Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); |
10380 | } |
10381 | |
10382 | // Instantiate the members of this class template specialization. |
10383 | Def = cast_or_null<ClassTemplateSpecializationDecl>( |
10384 | Specialization->getDefinition()); |
10385 | if (Def) { |
10386 | TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); |
10387 | // Fix a TSK_ExplicitInstantiationDeclaration followed by a |
10388 | // TSK_ExplicitInstantiationDefinition |
10389 | if (Old_TSK == TSK_ExplicitInstantiationDeclaration && |
10390 | (TSK == TSK_ExplicitInstantiationDefinition || |
10391 | DLLImportExplicitInstantiationDef)) { |
10392 | // FIXME: Need to notify the ASTMutationListener that we did this. |
10393 | Def->setTemplateSpecializationKind(TSK); |
10394 | |
10395 | if (!getDLLAttr(Def) && getDLLAttr(Specialization) && |
10396 | (Context.getTargetInfo().shouldDLLImportComdatSymbols() && |
10397 | !Context.getTargetInfo().getTriple().isPS())) { |
10398 | // An explicit instantiation definition can add a dll attribute to a |
10399 | // template with a previous instantiation declaration. MinGW doesn't |
10400 | // allow this. |
10401 | auto *A = cast<InheritableAttr>( |
10402 | Val: getDLLAttr(Specialization)->clone(C&: getASTContext())); |
10403 | A->setInherited(true); |
10404 | Def->addAttr(A: A); |
10405 | dllExportImportClassTemplateSpecialization(S&: *this, Def); |
10406 | } |
10407 | } |
10408 | |
10409 | // Fix a TSK_ImplicitInstantiation followed by a |
10410 | // TSK_ExplicitInstantiationDefinition |
10411 | bool NewlyDLLExported = |
10412 | !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>(); |
10413 | if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported && |
10414 | (Context.getTargetInfo().shouldDLLImportComdatSymbols() && |
10415 | !Context.getTargetInfo().getTriple().isPS())) { |
10416 | // An explicit instantiation definition can add a dll attribute to a |
10417 | // template with a previous implicit instantiation. MinGW doesn't allow |
10418 | // this. We limit clang to only adding dllexport, to avoid potentially |
10419 | // strange codegen behavior. For example, if we extend this conditional |
10420 | // to dllimport, and we have a source file calling a method on an |
10421 | // implicitly instantiated template class instance and then declaring a |
10422 | // dllimport explicit instantiation definition for the same template |
10423 | // class, the codegen for the method call will not respect the dllimport, |
10424 | // while it will with cl. The Def will already have the DLL attribute, |
10425 | // since the Def and Specialization will be the same in the case of |
10426 | // Old_TSK == TSK_ImplicitInstantiation, and we already added the |
10427 | // attribute to the Specialization; we just need to make it take effect. |
10428 | assert(Def == Specialization && |
10429 | "Def and Specialization should match for implicit instantiation" ); |
10430 | dllExportImportClassTemplateSpecialization(S&: *this, Def); |
10431 | } |
10432 | |
10433 | // In MinGW mode, export the template instantiation if the declaration |
10434 | // was marked dllexport. |
10435 | if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && |
10436 | Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() && |
10437 | PrevDecl->hasAttr<DLLExportAttr>()) { |
10438 | dllExportImportClassTemplateSpecialization(S&: *this, Def); |
10439 | } |
10440 | |
10441 | // Set the template specialization kind. Make sure it is set before |
10442 | // instantiating the members which will trigger ASTConsumer callbacks. |
10443 | Specialization->setTemplateSpecializationKind(TSK); |
10444 | InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK); |
10445 | } else { |
10446 | |
10447 | // Set the template specialization kind. |
10448 | Specialization->setTemplateSpecializationKind(TSK); |
10449 | } |
10450 | |
10451 | return Specialization; |
10452 | } |
10453 | |
10454 | // Explicit instantiation of a member class of a class template. |
10455 | DeclResult |
10456 | Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, |
10457 | SourceLocation TemplateLoc, unsigned TagSpec, |
10458 | SourceLocation KWLoc, CXXScopeSpec &SS, |
10459 | IdentifierInfo *Name, SourceLocation NameLoc, |
10460 | const ParsedAttributesView &Attr) { |
10461 | |
10462 | bool Owned = false; |
10463 | bool IsDependent = false; |
10464 | Decl *TagD = ActOnTag(S, TagSpec, TUK: Sema::TUK_Reference, KWLoc, SS, Name, |
10465 | NameLoc, Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(), |
10466 | TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(), |
10467 | ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false, |
10468 | /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get(); |
10469 | assert(!IsDependent && "explicit instantiation of dependent name not yet handled" ); |
10470 | |
10471 | if (!TagD) |
10472 | return true; |
10473 | |
10474 | TagDecl *Tag = cast<TagDecl>(Val: TagD); |
10475 | assert(!Tag->isEnum() && "shouldn't see enumerations here" ); |
10476 | |
10477 | if (Tag->isInvalidDecl()) |
10478 | return true; |
10479 | |
10480 | CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag); |
10481 | CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); |
10482 | if (!Pattern) { |
10483 | Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) |
10484 | << Context.getTypeDeclType(Record); |
10485 | Diag(Record->getLocation(), diag::note_nontemplate_decl_here); |
10486 | return true; |
10487 | } |
10488 | |
10489 | // C++0x [temp.explicit]p2: |
10490 | // If the explicit instantiation is for a class or member class, the |
10491 | // elaborated-type-specifier in the declaration shall include a |
10492 | // simple-template-id. |
10493 | // |
10494 | // C++98 has the same restriction, just worded differently. |
10495 | if (!ScopeSpecifierHasTemplateId(SS)) |
10496 | Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) |
10497 | << Record << SS.getRange(); |
10498 | |
10499 | // C++0x [temp.explicit]p2: |
10500 | // There are two forms of explicit instantiation: an explicit instantiation |
10501 | // definition and an explicit instantiation declaration. An explicit |
10502 | // instantiation declaration begins with the extern keyword. [...] |
10503 | TemplateSpecializationKind TSK |
10504 | = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition |
10505 | : TSK_ExplicitInstantiationDeclaration; |
10506 | |
10507 | CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK); |
10508 | |
10509 | // Verify that it is okay to explicitly instantiate here. |
10510 | CXXRecordDecl *PrevDecl |
10511 | = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl()); |
10512 | if (!PrevDecl && Record->getDefinition()) |
10513 | PrevDecl = Record; |
10514 | if (PrevDecl) { |
10515 | MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); |
10516 | bool HasNoEffect = false; |
10517 | assert(MSInfo && "No member specialization information?" ); |
10518 | if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, |
10519 | PrevDecl, |
10520 | MSInfo->getTemplateSpecializationKind(), |
10521 | MSInfo->getPointOfInstantiation(), |
10522 | HasNoEffect)) |
10523 | return true; |
10524 | if (HasNoEffect) |
10525 | return TagD; |
10526 | } |
10527 | |
10528 | CXXRecordDecl *RecordDef |
10529 | = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition()); |
10530 | if (!RecordDef) { |
10531 | // C++ [temp.explicit]p3: |
10532 | // A definition of a member class of a class template shall be in scope |
10533 | // at the point of an explicit instantiation of the member class. |
10534 | CXXRecordDecl *Def |
10535 | = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition()); |
10536 | if (!Def) { |
10537 | Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) |
10538 | << 0 << Record->getDeclName() << Record->getDeclContext(); |
10539 | Diag(Pattern->getLocation(), diag::note_forward_declaration) |
10540 | << Pattern; |
10541 | return true; |
10542 | } else { |
10543 | if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def, |
10544 | TemplateArgs: getTemplateInstantiationArgs(Record), |
10545 | TSK)) |
10546 | return true; |
10547 | |
10548 | RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition()); |
10549 | if (!RecordDef) |
10550 | return true; |
10551 | } |
10552 | } |
10553 | |
10554 | // Instantiate all of the members of the class. |
10555 | InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef, |
10556 | TemplateArgs: getTemplateInstantiationArgs(Record), TSK); |
10557 | |
10558 | if (TSK == TSK_ExplicitInstantiationDefinition) |
10559 | MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true); |
10560 | |
10561 | // FIXME: We don't have any representation for explicit instantiations of |
10562 | // member classes. Such a representation is not needed for compilation, but it |
10563 | // should be available for clients that want to see all of the declarations in |
10564 | // the source code. |
10565 | return TagD; |
10566 | } |
10567 | |
10568 | DeclResult Sema::ActOnExplicitInstantiation(Scope *S, |
10569 | SourceLocation ExternLoc, |
10570 | SourceLocation TemplateLoc, |
10571 | Declarator &D) { |
10572 | // Explicit instantiations always require a name. |
10573 | // TODO: check if/when DNInfo should replace Name. |
10574 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
10575 | DeclarationName Name = NameInfo.getName(); |
10576 | if (!Name) { |
10577 | if (!D.isInvalidType()) |
10578 | Diag(D.getDeclSpec().getBeginLoc(), |
10579 | diag::err_explicit_instantiation_requires_name) |
10580 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); |
10581 | |
10582 | return true; |
10583 | } |
10584 | |
10585 | // The scope passed in may not be a decl scope. Zip up the scope tree until |
10586 | // we find one that is. |
10587 | while ((S->getFlags() & Scope::DeclScope) == 0 || |
10588 | (S->getFlags() & Scope::TemplateParamScope) != 0) |
10589 | S = S->getParent(); |
10590 | |
10591 | // Determine the type of the declaration. |
10592 | TypeSourceInfo *T = GetTypeForDeclarator(D); |
10593 | QualType R = T->getType(); |
10594 | if (R.isNull()) |
10595 | return true; |
10596 | |
10597 | // C++ [dcl.stc]p1: |
10598 | // A storage-class-specifier shall not be specified in [...] an explicit |
10599 | // instantiation (14.7.2) directive. |
10600 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { |
10601 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) |
10602 | << Name; |
10603 | return true; |
10604 | } else if (D.getDeclSpec().getStorageClassSpec() |
10605 | != DeclSpec::SCS_unspecified) { |
10606 | // Complain about then remove the storage class specifier. |
10607 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class) |
10608 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); |
10609 | |
10610 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
10611 | } |
10612 | |
10613 | // C++0x [temp.explicit]p1: |
10614 | // [...] An explicit instantiation of a function template shall not use the |
10615 | // inline or constexpr specifiers. |
10616 | // Presumably, this also applies to member functions of class templates as |
10617 | // well. |
10618 | if (D.getDeclSpec().isInlineSpecified()) |
10619 | Diag(D.getDeclSpec().getInlineSpecLoc(), |
10620 | getLangOpts().CPlusPlus11 ? |
10621 | diag::err_explicit_instantiation_inline : |
10622 | diag::warn_explicit_instantiation_inline_0x) |
10623 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); |
10624 | if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType()) |
10625 | // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is |
10626 | // not already specified. |
10627 | Diag(D.getDeclSpec().getConstexprSpecLoc(), |
10628 | diag::err_explicit_instantiation_constexpr); |
10629 | |
10630 | // A deduction guide is not on the list of entities that can be explicitly |
10631 | // instantiated. |
10632 | if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { |
10633 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized) |
10634 | << /*explicit instantiation*/ 0; |
10635 | return true; |
10636 | } |
10637 | |
10638 | // C++0x [temp.explicit]p2: |
10639 | // There are two forms of explicit instantiation: an explicit instantiation |
10640 | // definition and an explicit instantiation declaration. An explicit |
10641 | // instantiation declaration begins with the extern keyword. [...] |
10642 | TemplateSpecializationKind TSK |
10643 | = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition |
10644 | : TSK_ExplicitInstantiationDeclaration; |
10645 | |
10646 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName); |
10647 | LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec()); |
10648 | |
10649 | if (!R->isFunctionType()) { |
10650 | // C++ [temp.explicit]p1: |
10651 | // A [...] static data member of a class template can be explicitly |
10652 | // instantiated from the member definition associated with its class |
10653 | // template. |
10654 | // C++1y [temp.explicit]p1: |
10655 | // A [...] variable [...] template specialization can be explicitly |
10656 | // instantiated from its template. |
10657 | if (Previous.isAmbiguous()) |
10658 | return true; |
10659 | |
10660 | VarDecl *Prev = Previous.getAsSingle<VarDecl>(); |
10661 | VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>(); |
10662 | |
10663 | if (!PrevTemplate) { |
10664 | if (!Prev || !Prev->isStaticDataMember()) { |
10665 | // We expect to see a static data member here. |
10666 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) |
10667 | << Name; |
10668 | for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); |
10669 | P != PEnd; ++P) |
10670 | Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); |
10671 | return true; |
10672 | } |
10673 | |
10674 | if (!Prev->getInstantiatedFromStaticDataMember()) { |
10675 | // FIXME: Check for explicit specialization? |
10676 | Diag(D.getIdentifierLoc(), |
10677 | diag::err_explicit_instantiation_data_member_not_instantiated) |
10678 | << Prev; |
10679 | Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); |
10680 | // FIXME: Can we provide a note showing where this was declared? |
10681 | return true; |
10682 | } |
10683 | } else { |
10684 | // Explicitly instantiate a variable template. |
10685 | |
10686 | // C++1y [dcl.spec.auto]p6: |
10687 | // ... A program that uses auto or decltype(auto) in a context not |
10688 | // explicitly allowed in this section is ill-formed. |
10689 | // |
10690 | // This includes auto-typed variable template instantiations. |
10691 | if (R->isUndeducedType()) { |
10692 | Diag(T->getTypeLoc().getBeginLoc(), |
10693 | diag::err_auto_not_allowed_var_inst); |
10694 | return true; |
10695 | } |
10696 | |
10697 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { |
10698 | // C++1y [temp.explicit]p3: |
10699 | // If the explicit instantiation is for a variable, the unqualified-id |
10700 | // in the declaration shall be a template-id. |
10701 | Diag(D.getIdentifierLoc(), |
10702 | diag::err_explicit_instantiation_without_template_id) |
10703 | << PrevTemplate; |
10704 | Diag(PrevTemplate->getLocation(), |
10705 | diag::note_explicit_instantiation_here); |
10706 | return true; |
10707 | } |
10708 | |
10709 | // Translate the parser's template argument list into our AST format. |
10710 | TemplateArgumentListInfo TemplateArgs = |
10711 | makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId); |
10712 | |
10713 | DeclResult Res = CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, |
10714 | TemplateNameLoc: D.getIdentifierLoc(), TemplateArgs); |
10715 | if (Res.isInvalid()) |
10716 | return true; |
10717 | |
10718 | if (!Res.isUsable()) { |
10719 | // We somehow specified dependent template arguments in an explicit |
10720 | // instantiation. This should probably only happen during error |
10721 | // recovery. |
10722 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent); |
10723 | return true; |
10724 | } |
10725 | |
10726 | // Ignore access control bits, we don't need them for redeclaration |
10727 | // checking. |
10728 | Prev = cast<VarDecl>(Val: Res.get()); |
10729 | } |
10730 | |
10731 | // C++0x [temp.explicit]p2: |
10732 | // If the explicit instantiation is for a member function, a member class |
10733 | // or a static data member of a class template specialization, the name of |
10734 | // the class template specialization in the qualified-id for the member |
10735 | // name shall be a simple-template-id. |
10736 | // |
10737 | // C++98 has the same restriction, just worded differently. |
10738 | // |
10739 | // This does not apply to variable template specializations, where the |
10740 | // template-id is in the unqualified-id instead. |
10741 | if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate) |
10742 | Diag(D.getIdentifierLoc(), |
10743 | diag::ext_explicit_instantiation_without_qualified_id) |
10744 | << Prev << D.getCXXScopeSpec().getRange(); |
10745 | |
10746 | CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK); |
10747 | |
10748 | // Verify that it is okay to explicitly instantiate here. |
10749 | TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind(); |
10750 | SourceLocation POI = Prev->getPointOfInstantiation(); |
10751 | bool HasNoEffect = false; |
10752 | if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, |
10753 | PrevTSK, POI, HasNoEffect)) |
10754 | return true; |
10755 | |
10756 | if (!HasNoEffect) { |
10757 | // Instantiate static data member or variable template. |
10758 | Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc()); |
10759 | // Merge attributes. |
10760 | ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes()); |
10761 | if (TSK == TSK_ExplicitInstantiationDefinition) |
10762 | InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev); |
10763 | } |
10764 | |
10765 | // Check the new variable specialization against the parsed input. |
10766 | if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) { |
10767 | Diag(T->getTypeLoc().getBeginLoc(), |
10768 | diag::err_invalid_var_template_spec_type) |
10769 | << 0 << PrevTemplate << R << Prev->getType(); |
10770 | Diag(PrevTemplate->getLocation(), diag::note_template_declared_here) |
10771 | << 2 << PrevTemplate->getDeclName(); |
10772 | return true; |
10773 | } |
10774 | |
10775 | // FIXME: Create an ExplicitInstantiation node? |
10776 | return (Decl*) nullptr; |
10777 | } |
10778 | |
10779 | // If the declarator is a template-id, translate the parser's template |
10780 | // argument list into our AST format. |
10781 | bool HasExplicitTemplateArgs = false; |
10782 | TemplateArgumentListInfo TemplateArgs; |
10783 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { |
10784 | TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId); |
10785 | HasExplicitTemplateArgs = true; |
10786 | } |
10787 | |
10788 | // C++ [temp.explicit]p1: |
10789 | // A [...] function [...] can be explicitly instantiated from its template. |
10790 | // A member function [...] of a class template can be explicitly |
10791 | // instantiated from the member definition associated with its class |
10792 | // template. |
10793 | UnresolvedSet<8> TemplateMatches; |
10794 | FunctionDecl *NonTemplateMatch = nullptr; |
10795 | TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc()); |
10796 | for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); |
10797 | P != PEnd; ++P) { |
10798 | NamedDecl *Prev = *P; |
10799 | if (!HasExplicitTemplateArgs) { |
10800 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) { |
10801 | QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(), |
10802 | /*AdjustExceptionSpec*/true); |
10803 | if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) { |
10804 | if (Method->getPrimaryTemplate()) { |
10805 | TemplateMatches.addDecl(Method, P.getAccess()); |
10806 | } else { |
10807 | // FIXME: Can this assert ever happen? Needs a test. |
10808 | assert(!NonTemplateMatch && "Multiple NonTemplateMatches" ); |
10809 | NonTemplateMatch = Method; |
10810 | } |
10811 | } |
10812 | } |
10813 | } |
10814 | |
10815 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev); |
10816 | if (!FunTmpl) |
10817 | continue; |
10818 | |
10819 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
10820 | FunctionDecl *Specialization = nullptr; |
10821 | if (TemplateDeductionResult TDK = DeduceTemplateArguments( |
10822 | FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R, |
10823 | Specialization, Info); |
10824 | TDK != TemplateDeductionResult::Success) { |
10825 | // Keep track of almost-matches. |
10826 | FailedCandidates.addCandidate() |
10827 | .set(P.getPair(), FunTmpl->getTemplatedDecl(), |
10828 | MakeDeductionFailureInfo(Context, TDK, Info)); |
10829 | (void)TDK; |
10830 | continue; |
10831 | } |
10832 | |
10833 | // Target attributes are part of the cuda function signature, so |
10834 | // the cuda target of the instantiated function must match that of its |
10835 | // template. Given that C++ template deduction does not take |
10836 | // target attributes into account, we reject candidates here that |
10837 | // have a different target. |
10838 | if (LangOpts.CUDA && |
10839 | IdentifyCUDATarget(D: Specialization, |
10840 | /* IgnoreImplicitHDAttr = */ true) != |
10841 | IdentifyCUDATarget(Attrs: D.getDeclSpec().getAttributes())) { |
10842 | FailedCandidates.addCandidate().set( |
10843 | P.getPair(), FunTmpl->getTemplatedDecl(), |
10844 | MakeDeductionFailureInfo( |
10845 | Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info)); |
10846 | continue; |
10847 | } |
10848 | |
10849 | TemplateMatches.addDecl(Specialization, P.getAccess()); |
10850 | } |
10851 | |
10852 | FunctionDecl *Specialization = NonTemplateMatch; |
10853 | if (!Specialization) { |
10854 | // Find the most specialized function template specialization. |
10855 | UnresolvedSetIterator Result = getMostSpecialized( |
10856 | TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates, |
10857 | D.getIdentifierLoc(), |
10858 | PDiag(diag::err_explicit_instantiation_not_known) << Name, |
10859 | PDiag(diag::err_explicit_instantiation_ambiguous) << Name, |
10860 | PDiag(diag::note_explicit_instantiation_candidate)); |
10861 | |
10862 | if (Result == TemplateMatches.end()) |
10863 | return true; |
10864 | |
10865 | // Ignore access control bits, we don't need them for redeclaration checking. |
10866 | Specialization = cast<FunctionDecl>(Val: *Result); |
10867 | } |
10868 | |
10869 | // C++11 [except.spec]p4 |
10870 | // In an explicit instantiation an exception-specification may be specified, |
10871 | // but is not required. |
10872 | // If an exception-specification is specified in an explicit instantiation |
10873 | // directive, it shall be compatible with the exception-specifications of |
10874 | // other declarations of that function. |
10875 | if (auto *FPT = R->getAs<FunctionProtoType>()) |
10876 | if (FPT->hasExceptionSpec()) { |
10877 | unsigned DiagID = |
10878 | diag::err_mismatched_exception_spec_explicit_instantiation; |
10879 | if (getLangOpts().MicrosoftExt) |
10880 | DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation; |
10881 | bool Result = CheckEquivalentExceptionSpec( |
10882 | PDiag(DiagID) << Specialization->getType(), |
10883 | PDiag(diag::note_explicit_instantiation_here), |
10884 | Specialization->getType()->getAs<FunctionProtoType>(), |
10885 | Specialization->getLocation(), FPT, D.getBeginLoc()); |
10886 | // In Microsoft mode, mismatching exception specifications just cause a |
10887 | // warning. |
10888 | if (!getLangOpts().MicrosoftExt && Result) |
10889 | return true; |
10890 | } |
10891 | |
10892 | if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { |
10893 | Diag(D.getIdentifierLoc(), |
10894 | diag::err_explicit_instantiation_member_function_not_instantiated) |
10895 | << Specialization |
10896 | << (Specialization->getTemplateSpecializationKind() == |
10897 | TSK_ExplicitSpecialization); |
10898 | Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); |
10899 | return true; |
10900 | } |
10901 | |
10902 | FunctionDecl *PrevDecl = Specialization->getPreviousDecl(); |
10903 | if (!PrevDecl && Specialization->isThisDeclarationADefinition()) |
10904 | PrevDecl = Specialization; |
10905 | |
10906 | if (PrevDecl) { |
10907 | bool HasNoEffect = false; |
10908 | if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, |
10909 | PrevDecl, |
10910 | PrevDecl->getTemplateSpecializationKind(), |
10911 | PrevDecl->getPointOfInstantiation(), |
10912 | HasNoEffect)) |
10913 | return true; |
10914 | |
10915 | // FIXME: We may still want to build some representation of this |
10916 | // explicit specialization. |
10917 | if (HasNoEffect) |
10918 | return (Decl*) nullptr; |
10919 | } |
10920 | |
10921 | // HACK: libc++ has a bug where it attempts to explicitly instantiate the |
10922 | // functions |
10923 | // valarray<size_t>::valarray(size_t) and |
10924 | // valarray<size_t>::~valarray() |
10925 | // that it declared to have internal linkage with the internal_linkage |
10926 | // attribute. Ignore the explicit instantiation declaration in this case. |
10927 | if (Specialization->hasAttr<InternalLinkageAttr>() && |
10928 | TSK == TSK_ExplicitInstantiationDeclaration) { |
10929 | if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext())) |
10930 | if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray" ) && |
10931 | RD->isInStdNamespace()) |
10932 | return (Decl*) nullptr; |
10933 | } |
10934 | |
10935 | ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes()); |
10936 | |
10937 | // In MSVC mode, dllimported explicit instantiation definitions are treated as |
10938 | // instantiation declarations. |
10939 | if (TSK == TSK_ExplicitInstantiationDefinition && |
10940 | Specialization->hasAttr<DLLImportAttr>() && |
10941 | Context.getTargetInfo().getCXXABI().isMicrosoft()) |
10942 | TSK = TSK_ExplicitInstantiationDeclaration; |
10943 | |
10944 | Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc()); |
10945 | |
10946 | if (Specialization->isDefined()) { |
10947 | // Let the ASTConsumer know that this function has been explicitly |
10948 | // instantiated now, and its linkage might have changed. |
10949 | Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization)); |
10950 | } else if (TSK == TSK_ExplicitInstantiationDefinition) |
10951 | InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization); |
10952 | |
10953 | // C++0x [temp.explicit]p2: |
10954 | // If the explicit instantiation is for a member function, a member class |
10955 | // or a static data member of a class template specialization, the name of |
10956 | // the class template specialization in the qualified-id for the member |
10957 | // name shall be a simple-template-id. |
10958 | // |
10959 | // C++98 has the same restriction, just worded differently. |
10960 | FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); |
10961 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl && |
10962 | D.getCXXScopeSpec().isSet() && |
10963 | !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) |
10964 | Diag(D.getIdentifierLoc(), |
10965 | diag::ext_explicit_instantiation_without_qualified_id) |
10966 | << Specialization << D.getCXXScopeSpec().getRange(); |
10967 | |
10968 | CheckExplicitInstantiation( |
10969 | *this, |
10970 | FunTmpl ? (NamedDecl *)FunTmpl |
10971 | : Specialization->getInstantiatedFromMemberFunction(), |
10972 | D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK); |
10973 | |
10974 | // FIXME: Create some kind of ExplicitInstantiationDecl here. |
10975 | return (Decl*) nullptr; |
10976 | } |
10977 | |
10978 | TypeResult |
10979 | Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, |
10980 | const CXXScopeSpec &SS, IdentifierInfo *Name, |
10981 | SourceLocation TagLoc, SourceLocation NameLoc) { |
10982 | // This has to hold, because SS is expected to be defined. |
10983 | assert(Name && "Expected a name in a dependent tag" ); |
10984 | |
10985 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
10986 | if (!NNS) |
10987 | return true; |
10988 | |
10989 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec); |
10990 | |
10991 | if (TUK == TUK_Declaration || TUK == TUK_Definition) { |
10992 | Diag(NameLoc, diag::err_dependent_tag_decl) |
10993 | << (TUK == TUK_Definition) << llvm::to_underlying(Kind) |
10994 | << SS.getRange(); |
10995 | return true; |
10996 | } |
10997 | |
10998 | // Create the resulting type. |
10999 | ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind); |
11000 | QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name); |
11001 | |
11002 | // Create type-source location information for this type. |
11003 | TypeLocBuilder TLB; |
11004 | DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result); |
11005 | TL.setElaboratedKeywordLoc(TagLoc); |
11006 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
11007 | TL.setNameLoc(NameLoc); |
11008 | return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result)); |
11009 | } |
11010 | |
11011 | TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, |
11012 | const CXXScopeSpec &SS, |
11013 | const IdentifierInfo &II, |
11014 | SourceLocation IdLoc, |
11015 | ImplicitTypenameContext IsImplicitTypename) { |
11016 | if (SS.isInvalid()) |
11017 | return true; |
11018 | |
11019 | if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) |
11020 | Diag(TypenameLoc, |
11021 | getLangOpts().CPlusPlus11 ? |
11022 | diag::warn_cxx98_compat_typename_outside_of_template : |
11023 | diag::ext_typename_outside_of_template) |
11024 | << FixItHint::CreateRemoval(TypenameLoc); |
11025 | |
11026 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
11027 | TypeSourceInfo *TSI = nullptr; |
11028 | QualType T = |
11029 | CheckTypenameType(Keyword: (TypenameLoc.isValid() || |
11030 | IsImplicitTypename == ImplicitTypenameContext::Yes) |
11031 | ? ElaboratedTypeKeyword::Typename |
11032 | : ElaboratedTypeKeyword::None, |
11033 | KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI, |
11034 | /*DeducedTSTContext=*/true); |
11035 | if (T.isNull()) |
11036 | return true; |
11037 | return CreateParsedType(T, TInfo: TSI); |
11038 | } |
11039 | |
11040 | TypeResult |
11041 | Sema::ActOnTypenameType(Scope *S, |
11042 | SourceLocation TypenameLoc, |
11043 | const CXXScopeSpec &SS, |
11044 | SourceLocation TemplateKWLoc, |
11045 | TemplateTy TemplateIn, |
11046 | IdentifierInfo *TemplateII, |
11047 | SourceLocation TemplateIILoc, |
11048 | SourceLocation LAngleLoc, |
11049 | ASTTemplateArgsPtr TemplateArgsIn, |
11050 | SourceLocation RAngleLoc) { |
11051 | if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) |
11052 | Diag(TypenameLoc, |
11053 | getLangOpts().CPlusPlus11 ? |
11054 | diag::warn_cxx98_compat_typename_outside_of_template : |
11055 | diag::ext_typename_outside_of_template) |
11056 | << FixItHint::CreateRemoval(TypenameLoc); |
11057 | |
11058 | // Strangely, non-type results are not ignored by this lookup, so the |
11059 | // program is ill-formed if it finds an injected-class-name. |
11060 | if (TypenameLoc.isValid()) { |
11061 | auto *LookupRD = |
11062 | dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false)); |
11063 | if (LookupRD && LookupRD->getIdentifier() == TemplateII) { |
11064 | Diag(TemplateIILoc, |
11065 | diag::ext_out_of_line_qualified_id_type_names_constructor) |
11066 | << TemplateII << 0 /*injected-class-name used as template name*/ |
11067 | << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/); |
11068 | } |
11069 | } |
11070 | |
11071 | // Translate the parser's template argument list in our AST format. |
11072 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
11073 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
11074 | |
11075 | TemplateName Template = TemplateIn.get(); |
11076 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
11077 | // Construct a dependent template specialization type. |
11078 | assert(DTN && "dependent template has non-dependent name?" ); |
11079 | assert(DTN->getQualifier() == SS.getScopeRep()); |
11080 | QualType T = Context.getDependentTemplateSpecializationType( |
11081 | Keyword: ElaboratedTypeKeyword::Typename, NNS: DTN->getQualifier(), |
11082 | Name: DTN->getIdentifier(), Args: TemplateArgs.arguments()); |
11083 | |
11084 | // Create source-location information for this type. |
11085 | TypeLocBuilder Builder; |
11086 | DependentTemplateSpecializationTypeLoc SpecTL |
11087 | = Builder.push<DependentTemplateSpecializationTypeLoc>(T); |
11088 | SpecTL.setElaboratedKeywordLoc(TypenameLoc); |
11089 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
11090 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
11091 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
11092 | SpecTL.setLAngleLoc(LAngleLoc); |
11093 | SpecTL.setRAngleLoc(RAngleLoc); |
11094 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
11095 | SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo()); |
11096 | return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T)); |
11097 | } |
11098 | |
11099 | QualType T = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs); |
11100 | if (T.isNull()) |
11101 | return true; |
11102 | |
11103 | // Provide source-location information for the template specialization type. |
11104 | TypeLocBuilder Builder; |
11105 | TemplateSpecializationTypeLoc SpecTL |
11106 | = Builder.push<TemplateSpecializationTypeLoc>(T); |
11107 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
11108 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
11109 | SpecTL.setLAngleLoc(LAngleLoc); |
11110 | SpecTL.setRAngleLoc(RAngleLoc); |
11111 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
11112 | SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo()); |
11113 | |
11114 | T = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::Typename, |
11115 | NNS: SS.getScopeRep(), NamedType: T); |
11116 | ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); |
11117 | TL.setElaboratedKeywordLoc(TypenameLoc); |
11118 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
11119 | |
11120 | TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); |
11121 | return CreateParsedType(T, TInfo: TSI); |
11122 | } |
11123 | |
11124 | |
11125 | /// Determine whether this failed name lookup should be treated as being |
11126 | /// disabled by a usage of std::enable_if. |
11127 | static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, |
11128 | SourceRange &CondRange, Expr *&Cond) { |
11129 | // We must be looking for a ::type... |
11130 | if (!II.isStr(Str: "type" )) |
11131 | return false; |
11132 | |
11133 | // ... within an explicitly-written template specialization... |
11134 | if (!NNS || !NNS.getNestedNameSpecifier()->getAsType()) |
11135 | return false; |
11136 | TypeLoc EnableIfTy = NNS.getTypeLoc(); |
11137 | TemplateSpecializationTypeLoc EnableIfTSTLoc = |
11138 | EnableIfTy.getAs<TemplateSpecializationTypeLoc>(); |
11139 | if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0) |
11140 | return false; |
11141 | const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr(); |
11142 | |
11143 | // ... which names a complete class template declaration... |
11144 | const TemplateDecl *EnableIfDecl = |
11145 | EnableIfTST->getTemplateName().getAsTemplateDecl(); |
11146 | if (!EnableIfDecl || EnableIfTST->isIncompleteType()) |
11147 | return false; |
11148 | |
11149 | // ... called "enable_if". |
11150 | const IdentifierInfo *EnableIfII = |
11151 | EnableIfDecl->getDeclName().getAsIdentifierInfo(); |
11152 | if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if" )) |
11153 | return false; |
11154 | |
11155 | // Assume the first template argument is the condition. |
11156 | CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange(); |
11157 | |
11158 | // Dig out the condition. |
11159 | Cond = nullptr; |
11160 | if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind() |
11161 | != TemplateArgument::Expression) |
11162 | return true; |
11163 | |
11164 | Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression(); |
11165 | |
11166 | // Ignore Boolean literals; they add no value. |
11167 | if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts())) |
11168 | Cond = nullptr; |
11169 | |
11170 | return true; |
11171 | } |
11172 | |
11173 | QualType |
11174 | Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, |
11175 | SourceLocation KeywordLoc, |
11176 | NestedNameSpecifierLoc QualifierLoc, |
11177 | const IdentifierInfo &II, |
11178 | SourceLocation IILoc, |
11179 | TypeSourceInfo **TSI, |
11180 | bool DeducedTSTContext) { |
11181 | QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc, |
11182 | DeducedTSTContext); |
11183 | if (T.isNull()) |
11184 | return QualType(); |
11185 | |
11186 | *TSI = Context.CreateTypeSourceInfo(T); |
11187 | if (isa<DependentNameType>(Val: T)) { |
11188 | DependentNameTypeLoc TL = |
11189 | (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>(); |
11190 | TL.setElaboratedKeywordLoc(KeywordLoc); |
11191 | TL.setQualifierLoc(QualifierLoc); |
11192 | TL.setNameLoc(IILoc); |
11193 | } else { |
11194 | ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>(); |
11195 | TL.setElaboratedKeywordLoc(KeywordLoc); |
11196 | TL.setQualifierLoc(QualifierLoc); |
11197 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc); |
11198 | } |
11199 | return T; |
11200 | } |
11201 | |
11202 | /// Build the type that describes a C++ typename specifier, |
11203 | /// e.g., "typename T::type". |
11204 | QualType |
11205 | Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, |
11206 | SourceLocation KeywordLoc, |
11207 | NestedNameSpecifierLoc QualifierLoc, |
11208 | const IdentifierInfo &II, |
11209 | SourceLocation IILoc, bool DeducedTSTContext) { |
11210 | CXXScopeSpec SS; |
11211 | SS.Adopt(Other: QualifierLoc); |
11212 | |
11213 | DeclContext *Ctx = nullptr; |
11214 | if (QualifierLoc) { |
11215 | Ctx = computeDeclContext(SS); |
11216 | if (!Ctx) { |
11217 | // If the nested-name-specifier is dependent and couldn't be |
11218 | // resolved to a type, build a typename type. |
11219 | assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); |
11220 | return Context.getDependentNameType(Keyword, |
11221 | NNS: QualifierLoc.getNestedNameSpecifier(), |
11222 | Name: &II); |
11223 | } |
11224 | |
11225 | // If the nested-name-specifier refers to the current instantiation, |
11226 | // the "typename" keyword itself is superfluous. In C++03, the |
11227 | // program is actually ill-formed. However, DR 382 (in C++0x CD1) |
11228 | // allows such extraneous "typename" keywords, and we retroactively |
11229 | // apply this DR to C++03 code with only a warning. In any case we continue. |
11230 | |
11231 | if (RequireCompleteDeclContext(SS, DC: Ctx)) |
11232 | return QualType(); |
11233 | } |
11234 | |
11235 | DeclarationName Name(&II); |
11236 | LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); |
11237 | if (Ctx) |
11238 | LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS); |
11239 | else |
11240 | LookupName(R&: Result, S: CurScope); |
11241 | unsigned DiagID = 0; |
11242 | Decl *Referenced = nullptr; |
11243 | switch (Result.getResultKind()) { |
11244 | case LookupResult::NotFound: { |
11245 | // If we're looking up 'type' within a template named 'enable_if', produce |
11246 | // a more specific diagnostic. |
11247 | SourceRange CondRange; |
11248 | Expr *Cond = nullptr; |
11249 | if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) { |
11250 | // If we have a condition, narrow it down to the specific failed |
11251 | // condition. |
11252 | if (Cond) { |
11253 | Expr *FailedCond; |
11254 | std::string FailedDescription; |
11255 | std::tie(args&: FailedCond, args&: FailedDescription) = |
11256 | findFailedBooleanCondition(Cond); |
11257 | |
11258 | Diag(FailedCond->getExprLoc(), |
11259 | diag::err_typename_nested_not_found_requirement) |
11260 | << FailedDescription |
11261 | << FailedCond->getSourceRange(); |
11262 | return QualType(); |
11263 | } |
11264 | |
11265 | Diag(CondRange.getBegin(), |
11266 | diag::err_typename_nested_not_found_enable_if) |
11267 | << Ctx << CondRange; |
11268 | return QualType(); |
11269 | } |
11270 | |
11271 | DiagID = Ctx ? diag::err_typename_nested_not_found |
11272 | : diag::err_unknown_typename; |
11273 | break; |
11274 | } |
11275 | |
11276 | case LookupResult::FoundUnresolvedValue: { |
11277 | // We found a using declaration that is a value. Most likely, the using |
11278 | // declaration itself is meant to have the 'typename' keyword. |
11279 | SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), |
11280 | IILoc); |
11281 | Diag(IILoc, diag::err_typename_refers_to_using_value_decl) |
11282 | << Name << Ctx << FullRange; |
11283 | if (UnresolvedUsingValueDecl *Using |
11284 | = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){ |
11285 | SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); |
11286 | Diag(Loc, diag::note_using_value_decl_missing_typename) |
11287 | << FixItHint::CreateInsertion(Loc, "typename " ); |
11288 | } |
11289 | } |
11290 | // Fall through to create a dependent typename type, from which we can recover |
11291 | // better. |
11292 | [[fallthrough]]; |
11293 | |
11294 | case LookupResult::NotFoundInCurrentInstantiation: |
11295 | // Okay, it's a member of an unknown instantiation. |
11296 | return Context.getDependentNameType(Keyword, |
11297 | NNS: QualifierLoc.getNestedNameSpecifier(), |
11298 | Name: &II); |
11299 | |
11300 | case LookupResult::Found: |
11301 | if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) { |
11302 | // C++ [class.qual]p2: |
11303 | // In a lookup in which function names are not ignored and the |
11304 | // nested-name-specifier nominates a class C, if the name specified |
11305 | // after the nested-name-specifier, when looked up in C, is the |
11306 | // injected-class-name of C [...] then the name is instead considered |
11307 | // to name the constructor of class C. |
11308 | // |
11309 | // Unlike in an elaborated-type-specifier, function names are not ignored |
11310 | // in typename-specifier lookup. However, they are ignored in all the |
11311 | // contexts where we form a typename type with no keyword (that is, in |
11312 | // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers). |
11313 | // |
11314 | // FIXME: That's not strictly true: mem-initializer-id lookup does not |
11315 | // ignore functions, but that appears to be an oversight. |
11316 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: Ctx); |
11317 | auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: Type); |
11318 | if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD && |
11319 | FoundRD->isInjectedClassName() && |
11320 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) |
11321 | Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor) |
11322 | << &II << 1 << 0 /*'typename' keyword used*/; |
11323 | |
11324 | // We found a type. Build an ElaboratedType, since the |
11325 | // typename-specifier was just sugar. |
11326 | MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false); |
11327 | return Context.getElaboratedType(Keyword, |
11328 | NNS: QualifierLoc.getNestedNameSpecifier(), |
11329 | NamedType: Context.getTypeDeclType(Decl: Type)); |
11330 | } |
11331 | |
11332 | // C++ [dcl.type.simple]p2: |
11333 | // A type-specifier of the form |
11334 | // typename[opt] nested-name-specifier[opt] template-name |
11335 | // is a placeholder for a deduced class type [...]. |
11336 | if (getLangOpts().CPlusPlus17) { |
11337 | if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) { |
11338 | if (!DeducedTSTContext) { |
11339 | QualType T(QualifierLoc |
11340 | ? QualifierLoc.getNestedNameSpecifier()->getAsType() |
11341 | : nullptr, 0); |
11342 | if (!T.isNull()) |
11343 | Diag(IILoc, diag::err_dependent_deduced_tst) |
11344 | << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T; |
11345 | else |
11346 | Diag(IILoc, diag::err_deduced_tst) |
11347 | << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)); |
11348 | NoteTemplateLocation(Decl: *TD); |
11349 | return QualType(); |
11350 | } |
11351 | return Context.getElaboratedType( |
11352 | Keyword, NNS: QualifierLoc.getNestedNameSpecifier(), |
11353 | NamedType: Context.getDeducedTemplateSpecializationType(Template: TemplateName(TD), |
11354 | DeducedType: QualType(), IsDependent: false)); |
11355 | } |
11356 | } |
11357 | |
11358 | DiagID = Ctx ? diag::err_typename_nested_not_type |
11359 | : diag::err_typename_not_type; |
11360 | Referenced = Result.getFoundDecl(); |
11361 | break; |
11362 | |
11363 | case LookupResult::FoundOverloaded: |
11364 | DiagID = Ctx ? diag::err_typename_nested_not_type |
11365 | : diag::err_typename_not_type; |
11366 | Referenced = *Result.begin(); |
11367 | break; |
11368 | |
11369 | case LookupResult::Ambiguous: |
11370 | return QualType(); |
11371 | } |
11372 | |
11373 | // If we get here, it's because name lookup did not find a |
11374 | // type. Emit an appropriate diagnostic and return an error. |
11375 | SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), |
11376 | IILoc); |
11377 | if (Ctx) |
11378 | Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx; |
11379 | else |
11380 | Diag(Loc: IILoc, DiagID) << FullRange << Name; |
11381 | if (Referenced) |
11382 | Diag(Referenced->getLocation(), |
11383 | Ctx ? diag::note_typename_member_refers_here |
11384 | : diag::note_typename_refers_here) |
11385 | << Name; |
11386 | return QualType(); |
11387 | } |
11388 | |
11389 | namespace { |
11390 | // See Sema::RebuildTypeInCurrentInstantiation |
11391 | class CurrentInstantiationRebuilder |
11392 | : public TreeTransform<CurrentInstantiationRebuilder> { |
11393 | SourceLocation Loc; |
11394 | DeclarationName Entity; |
11395 | |
11396 | public: |
11397 | typedef TreeTransform<CurrentInstantiationRebuilder> inherited; |
11398 | |
11399 | CurrentInstantiationRebuilder(Sema &SemaRef, |
11400 | SourceLocation Loc, |
11401 | DeclarationName Entity) |
11402 | : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), |
11403 | Loc(Loc), Entity(Entity) { } |
11404 | |
11405 | /// Determine whether the given type \p T has already been |
11406 | /// transformed. |
11407 | /// |
11408 | /// For the purposes of type reconstruction, a type has already been |
11409 | /// transformed if it is NULL or if it is not dependent. |
11410 | bool AlreadyTransformed(QualType T) { |
11411 | return T.isNull() || !T->isInstantiationDependentType(); |
11412 | } |
11413 | |
11414 | /// Returns the location of the entity whose type is being |
11415 | /// rebuilt. |
11416 | SourceLocation getBaseLocation() { return Loc; } |
11417 | |
11418 | /// Returns the name of the entity whose type is being rebuilt. |
11419 | DeclarationName getBaseEntity() { return Entity; } |
11420 | |
11421 | /// Sets the "base" location and entity when that |
11422 | /// information is known based on another transformation. |
11423 | void setBase(SourceLocation Loc, DeclarationName Entity) { |
11424 | this->Loc = Loc; |
11425 | this->Entity = Entity; |
11426 | } |
11427 | |
11428 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
11429 | // Lambdas never need to be transformed. |
11430 | return E; |
11431 | } |
11432 | }; |
11433 | } // end anonymous namespace |
11434 | |
11435 | /// Rebuilds a type within the context of the current instantiation. |
11436 | /// |
11437 | /// The type \p T is part of the type of an out-of-line member definition of |
11438 | /// a class template (or class template partial specialization) that was parsed |
11439 | /// and constructed before we entered the scope of the class template (or |
11440 | /// partial specialization thereof). This routine will rebuild that type now |
11441 | /// that we have entered the declarator's scope, which may produce different |
11442 | /// canonical types, e.g., |
11443 | /// |
11444 | /// \code |
11445 | /// template<typename T> |
11446 | /// struct X { |
11447 | /// typedef T* pointer; |
11448 | /// pointer data(); |
11449 | /// }; |
11450 | /// |
11451 | /// template<typename T> |
11452 | /// typename X<T>::pointer X<T>::data() { ... } |
11453 | /// \endcode |
11454 | /// |
11455 | /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, |
11456 | /// since we do not know that we can look into X<T> when we parsed the type. |
11457 | /// This function will rebuild the type, performing the lookup of "pointer" |
11458 | /// in X<T> and returning an ElaboratedType whose canonical type is the same |
11459 | /// as the canonical type of T*, allowing the return types of the out-of-line |
11460 | /// definition and the declaration to match. |
11461 | TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, |
11462 | SourceLocation Loc, |
11463 | DeclarationName Name) { |
11464 | if (!T || !T->getType()->isInstantiationDependentType()) |
11465 | return T; |
11466 | |
11467 | CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); |
11468 | return Rebuilder.TransformType(T); |
11469 | } |
11470 | |
11471 | ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { |
11472 | CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), |
11473 | DeclarationName()); |
11474 | return Rebuilder.TransformExpr(E); |
11475 | } |
11476 | |
11477 | bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { |
11478 | if (SS.isInvalid()) |
11479 | return true; |
11480 | |
11481 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
11482 | CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), |
11483 | DeclarationName()); |
11484 | NestedNameSpecifierLoc Rebuilt |
11485 | = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); |
11486 | if (!Rebuilt) |
11487 | return true; |
11488 | |
11489 | SS.Adopt(Other: Rebuilt); |
11490 | return false; |
11491 | } |
11492 | |
11493 | /// Rebuild the template parameters now that we know we're in a current |
11494 | /// instantiation. |
11495 | bool Sema::RebuildTemplateParamsInCurrentInstantiation( |
11496 | TemplateParameterList *Params) { |
11497 | for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
11498 | Decl *Param = Params->getParam(Idx: I); |
11499 | |
11500 | // There is nothing to rebuild in a type parameter. |
11501 | if (isa<TemplateTypeParmDecl>(Val: Param)) |
11502 | continue; |
11503 | |
11504 | // Rebuild the template parameter list of a template template parameter. |
11505 | if (TemplateTemplateParmDecl *TTP |
11506 | = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) { |
11507 | if (RebuildTemplateParamsInCurrentInstantiation( |
11508 | Params: TTP->getTemplateParameters())) |
11509 | return true; |
11510 | |
11511 | continue; |
11512 | } |
11513 | |
11514 | // Rebuild the type of a non-type template parameter. |
11515 | NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param); |
11516 | TypeSourceInfo *NewTSI |
11517 | = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(), |
11518 | Loc: NTTP->getLocation(), |
11519 | Name: NTTP->getDeclName()); |
11520 | if (!NewTSI) |
11521 | return true; |
11522 | |
11523 | if (NewTSI->getType()->isUndeducedType()) { |
11524 | // C++17 [temp.dep.expr]p3: |
11525 | // An id-expression is type-dependent if it contains |
11526 | // - an identifier associated by name lookup with a non-type |
11527 | // template-parameter declared with a type that contains a |
11528 | // placeholder type (7.1.7.4), |
11529 | NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI); |
11530 | } |
11531 | |
11532 | if (NewTSI != NTTP->getTypeSourceInfo()) { |
11533 | NTTP->setTypeSourceInfo(NewTSI); |
11534 | NTTP->setType(NewTSI->getType()); |
11535 | } |
11536 | } |
11537 | |
11538 | return false; |
11539 | } |
11540 | |
11541 | /// Produces a formatted string that describes the binding of |
11542 | /// template parameters to template arguments. |
11543 | std::string |
11544 | Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
11545 | const TemplateArgumentList &Args) { |
11546 | return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size()); |
11547 | } |
11548 | |
11549 | std::string |
11550 | Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
11551 | const TemplateArgument *Args, |
11552 | unsigned NumArgs) { |
11553 | SmallString<128> Str; |
11554 | llvm::raw_svector_ostream Out(Str); |
11555 | |
11556 | if (!Params || Params->size() == 0 || NumArgs == 0) |
11557 | return std::string(); |
11558 | |
11559 | for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
11560 | if (I >= NumArgs) |
11561 | break; |
11562 | |
11563 | if (I == 0) |
11564 | Out << "[with " ; |
11565 | else |
11566 | Out << ", " ; |
11567 | |
11568 | if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) { |
11569 | Out << Id->getName(); |
11570 | } else { |
11571 | Out << '$' << I; |
11572 | } |
11573 | |
11574 | Out << " = " ; |
11575 | Args[I].print(Policy: getPrintingPolicy(), Out, |
11576 | IncludeType: TemplateParameterList::shouldIncludeTypeForArgument( |
11577 | Policy: getPrintingPolicy(), TPL: Params, Idx: I)); |
11578 | } |
11579 | |
11580 | Out << ']'; |
11581 | return std::string(Out.str()); |
11582 | } |
11583 | |
11584 | void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, |
11585 | CachedTokens &Toks) { |
11586 | if (!FD) |
11587 | return; |
11588 | |
11589 | auto LPT = std::make_unique<LateParsedTemplate>(); |
11590 | |
11591 | // Take tokens to avoid allocations |
11592 | LPT->Toks.swap(RHS&: Toks); |
11593 | LPT->D = FnD; |
11594 | LPT->FPO = getCurFPFeatures(); |
11595 | LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT))); |
11596 | |
11597 | FD->setLateTemplateParsed(true); |
11598 | } |
11599 | |
11600 | void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) { |
11601 | if (!FD) |
11602 | return; |
11603 | FD->setLateTemplateParsed(false); |
11604 | } |
11605 | |
11606 | bool Sema::IsInsideALocalClassWithinATemplateFunction() { |
11607 | DeclContext *DC = CurContext; |
11608 | |
11609 | while (DC) { |
11610 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) { |
11611 | const FunctionDecl *FD = RD->isLocalClass(); |
11612 | return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate); |
11613 | } else if (DC->isTranslationUnit() || DC->isNamespace()) |
11614 | return false; |
11615 | |
11616 | DC = DC->getParent(); |
11617 | } |
11618 | return false; |
11619 | } |
11620 | |
11621 | namespace { |
11622 | /// Walk the path from which a declaration was instantiated, and check |
11623 | /// that every explicit specialization along that path is visible. This enforces |
11624 | /// C++ [temp.expl.spec]/6: |
11625 | /// |
11626 | /// If a template, a member template or a member of a class template is |
11627 | /// explicitly specialized then that specialization shall be declared before |
11628 | /// the first use of that specialization that would cause an implicit |
11629 | /// instantiation to take place, in every translation unit in which such a |
11630 | /// use occurs; no diagnostic is required. |
11631 | /// |
11632 | /// and also C++ [temp.class.spec]/1: |
11633 | /// |
11634 | /// A partial specialization shall be declared before the first use of a |
11635 | /// class template specialization that would make use of the partial |
11636 | /// specialization as the result of an implicit or explicit instantiation |
11637 | /// in every translation unit in which such a use occurs; no diagnostic is |
11638 | /// required. |
11639 | class ExplicitSpecializationVisibilityChecker { |
11640 | Sema &S; |
11641 | SourceLocation Loc; |
11642 | llvm::SmallVector<Module *, 8> Modules; |
11643 | Sema::AcceptableKind Kind; |
11644 | |
11645 | public: |
11646 | ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc, |
11647 | Sema::AcceptableKind Kind) |
11648 | : S(S), Loc(Loc), Kind(Kind) {} |
11649 | |
11650 | void check(NamedDecl *ND) { |
11651 | if (auto *FD = dyn_cast<FunctionDecl>(Val: ND)) |
11652 | return checkImpl(Spec: FD); |
11653 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND)) |
11654 | return checkImpl(Spec: RD); |
11655 | if (auto *VD = dyn_cast<VarDecl>(Val: ND)) |
11656 | return checkImpl(Spec: VD); |
11657 | if (auto *ED = dyn_cast<EnumDecl>(Val: ND)) |
11658 | return checkImpl(Spec: ED); |
11659 | } |
11660 | |
11661 | private: |
11662 | void diagnose(NamedDecl *D, bool IsPartialSpec) { |
11663 | auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization |
11664 | : Sema::MissingImportKind::ExplicitSpecialization; |
11665 | const bool Recover = true; |
11666 | |
11667 | // If we got a custom set of modules (because only a subset of the |
11668 | // declarations are interesting), use them, otherwise let |
11669 | // diagnoseMissingImport intelligently pick some. |
11670 | if (Modules.empty()) |
11671 | S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover); |
11672 | else |
11673 | S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover); |
11674 | } |
11675 | |
11676 | bool CheckMemberSpecialization(const NamedDecl *D) { |
11677 | return Kind == Sema::AcceptableKind::Visible |
11678 | ? S.hasVisibleMemberSpecialization(D) |
11679 | : S.hasReachableMemberSpecialization(D); |
11680 | } |
11681 | |
11682 | bool CheckExplicitSpecialization(const NamedDecl *D) { |
11683 | return Kind == Sema::AcceptableKind::Visible |
11684 | ? S.hasVisibleExplicitSpecialization(D) |
11685 | : S.hasReachableExplicitSpecialization(D); |
11686 | } |
11687 | |
11688 | bool CheckDeclaration(const NamedDecl *D) { |
11689 | return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D) |
11690 | : S.hasReachableDeclaration(D); |
11691 | } |
11692 | |
11693 | // Check a specific declaration. There are three problematic cases: |
11694 | // |
11695 | // 1) The declaration is an explicit specialization of a template |
11696 | // specialization. |
11697 | // 2) The declaration is an explicit specialization of a member of an |
11698 | // templated class. |
11699 | // 3) The declaration is an instantiation of a template, and that template |
11700 | // is an explicit specialization of a member of a templated class. |
11701 | // |
11702 | // We don't need to go any deeper than that, as the instantiation of the |
11703 | // surrounding class / etc is not triggered by whatever triggered this |
11704 | // instantiation, and thus should be checked elsewhere. |
11705 | template<typename SpecDecl> |
11706 | void checkImpl(SpecDecl *Spec) { |
11707 | bool IsHiddenExplicitSpecialization = false; |
11708 | if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { |
11709 | IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo() |
11710 | ? !CheckMemberSpecialization(D: Spec) |
11711 | : !CheckExplicitSpecialization(D: Spec); |
11712 | } else { |
11713 | checkInstantiated(Spec); |
11714 | } |
11715 | |
11716 | if (IsHiddenExplicitSpecialization) |
11717 | diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false); |
11718 | } |
11719 | |
11720 | void checkInstantiated(FunctionDecl *FD) { |
11721 | if (auto *TD = FD->getPrimaryTemplate()) |
11722 | checkTemplate(TD); |
11723 | } |
11724 | |
11725 | void checkInstantiated(CXXRecordDecl *RD) { |
11726 | auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD); |
11727 | if (!SD) |
11728 | return; |
11729 | |
11730 | auto From = SD->getSpecializedTemplateOrPartial(); |
11731 | if (auto *TD = From.dyn_cast<ClassTemplateDecl *>()) |
11732 | checkTemplate(TD); |
11733 | else if (auto *TD = |
11734 | From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { |
11735 | if (!CheckDeclaration(TD)) |
11736 | diagnose(TD, true); |
11737 | checkTemplate(TD); |
11738 | } |
11739 | } |
11740 | |
11741 | void checkInstantiated(VarDecl *RD) { |
11742 | auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD); |
11743 | if (!SD) |
11744 | return; |
11745 | |
11746 | auto From = SD->getSpecializedTemplateOrPartial(); |
11747 | if (auto *TD = From.dyn_cast<VarTemplateDecl *>()) |
11748 | checkTemplate(TD); |
11749 | else if (auto *TD = |
11750 | From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { |
11751 | if (!CheckDeclaration(TD)) |
11752 | diagnose(TD, true); |
11753 | checkTemplate(TD); |
11754 | } |
11755 | } |
11756 | |
11757 | void checkInstantiated(EnumDecl *FD) {} |
11758 | |
11759 | template<typename TemplDecl> |
11760 | void checkTemplate(TemplDecl *TD) { |
11761 | if (TD->isMemberSpecialization()) { |
11762 | if (!CheckMemberSpecialization(D: TD)) |
11763 | diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false); |
11764 | } |
11765 | } |
11766 | }; |
11767 | } // end anonymous namespace |
11768 | |
11769 | void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) { |
11770 | if (!getLangOpts().Modules) |
11771 | return; |
11772 | |
11773 | ExplicitSpecializationVisibilityChecker(*this, Loc, |
11774 | Sema::AcceptableKind::Visible) |
11775 | .check(ND: Spec); |
11776 | } |
11777 | |
11778 | void Sema::checkSpecializationReachability(SourceLocation Loc, |
11779 | NamedDecl *Spec) { |
11780 | if (!getLangOpts().CPlusPlusModules) |
11781 | return checkSpecializationVisibility(Loc, Spec); |
11782 | |
11783 | ExplicitSpecializationVisibilityChecker(*this, Loc, |
11784 | Sema::AcceptableKind::Reachable) |
11785 | .check(ND: Spec); |
11786 | } |
11787 | |
11788 | /// Returns the top most location responsible for the definition of \p N. |
11789 | /// If \p N is a a template specialization, this is the location |
11790 | /// of the top of the instantiation stack. |
11791 | /// Otherwise, the location of \p N is returned. |
11792 | SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const { |
11793 | if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty()) |
11794 | return N->getLocation(); |
11795 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) { |
11796 | if (!FD->isFunctionTemplateSpecialization()) |
11797 | return FD->getLocation(); |
11798 | } else if (!isa<ClassTemplateSpecializationDecl, |
11799 | VarTemplateSpecializationDecl>(Val: N)) { |
11800 | return N->getLocation(); |
11801 | } |
11802 | for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) { |
11803 | if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid()) |
11804 | continue; |
11805 | return CSC.PointOfInstantiation; |
11806 | } |
11807 | return N->getLocation(); |
11808 | } |
11809 | |