| File: | build/source/clang/lib/Sema/SemaTemplate.cpp |
| Warning: | line 1419, column 5 Value stored to 'RD' is never read |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 1 | //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | //===----------------------------------------------------------------------===// |
| 7 | // |
| 8 | // This file implements semantic analysis for C++ templates. |
| 9 | //===----------------------------------------------------------------------===// |
| 10 | |
| 11 | #include "TreeTransform.h" |
| 12 | #include "clang/AST/ASTConsumer.h" |
| 13 | #include "clang/AST/ASTContext.h" |
| 14 | #include "clang/AST/Decl.h" |
| 15 | #include "clang/AST/DeclFriend.h" |
| 16 | #include "clang/AST/DeclTemplate.h" |
| 17 | #include "clang/AST/Expr.h" |
| 18 | #include "clang/AST/ExprCXX.h" |
| 19 | #include "clang/AST/RecursiveASTVisitor.h" |
| 20 | #include "clang/AST/TemplateName.h" |
| 21 | #include "clang/AST/TypeVisitor.h" |
| 22 | #include "clang/Basic/Builtins.h" |
| 23 | #include "clang/Basic/DiagnosticSema.h" |
| 24 | #include "clang/Basic/LangOptions.h" |
| 25 | #include "clang/Basic/PartialDiagnostic.h" |
| 26 | #include "clang/Basic/Stack.h" |
| 27 | #include "clang/Basic/TargetInfo.h" |
| 28 | #include "clang/Sema/DeclSpec.h" |
| 29 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
| 30 | #include "clang/Sema/Initialization.h" |
| 31 | #include "clang/Sema/Lookup.h" |
| 32 | #include "clang/Sema/Overload.h" |
| 33 | #include "clang/Sema/ParsedTemplate.h" |
| 34 | #include "clang/Sema/Scope.h" |
| 35 | #include "clang/Sema/SemaInternal.h" |
| 36 | #include "clang/Sema/Template.h" |
| 37 | #include "clang/Sema/TemplateDeduction.h" |
| 38 | #include "llvm/ADT/SmallBitVector.h" |
| 39 | #include "llvm/ADT/SmallString.h" |
| 40 | #include "llvm/ADT/StringExtras.h" |
| 41 | |
| 42 | #include <iterator> |
| 43 | #include <optional> |
| 44 | using namespace clang; |
| 45 | using namespace sema; |
| 46 | |
| 47 | // Exported for use by Parser. |
| 48 | SourceRange |
| 49 | clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, |
| 50 | unsigned N) { |
| 51 | if (!N) return SourceRange(); |
| 52 | return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); |
| 53 | } |
| 54 | |
| 55 | unsigned Sema::getTemplateDepth(Scope *S) const { |
| 56 | unsigned Depth = 0; |
| 57 | |
| 58 | // Each template parameter scope represents one level of template parameter |
| 59 | // depth. |
| 60 | for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope; |
| 61 | TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) { |
| 62 | ++Depth; |
| 63 | } |
| 64 | |
| 65 | // Note that there are template parameters with the given depth. |
| 66 | auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); }; |
| 67 | |
| 68 | // Look for parameters of an enclosing generic lambda. We don't create a |
| 69 | // template parameter scope for these. |
| 70 | for (FunctionScopeInfo *FSI : getFunctionScopes()) { |
| 71 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) { |
| 72 | if (!LSI->TemplateParams.empty()) { |
| 73 | ParamsAtDepth(LSI->AutoTemplateParameterDepth); |
| 74 | break; |
| 75 | } |
| 76 | if (LSI->GLTemplateParameterList) { |
| 77 | ParamsAtDepth(LSI->GLTemplateParameterList->getDepth()); |
| 78 | break; |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // Look for parameters of an enclosing terse function template. We don't |
| 84 | // create a template parameter scope for these either. |
| 85 | for (const InventedTemplateParameterInfo &Info : |
| 86 | getInventedParameterInfos()) { |
| 87 | if (!Info.TemplateParams.empty()) { |
| 88 | ParamsAtDepth(Info.AutoTemplateParameterDepth); |
| 89 | break; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | return Depth; |
| 94 | } |
| 95 | |
| 96 | /// \brief Determine whether the declaration found is acceptable as the name |
| 97 | /// of a template and, if so, return that template declaration. Otherwise, |
| 98 | /// returns null. |
| 99 | /// |
| 100 | /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent |
| 101 | /// is true. In all other cases it will return a TemplateDecl (or null). |
| 102 | NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D, |
| 103 | bool AllowFunctionTemplates, |
| 104 | bool AllowDependent) { |
| 105 | D = D->getUnderlyingDecl(); |
| 106 | |
| 107 | if (isa<TemplateDecl>(D)) { |
| 108 | if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D)) |
| 109 | return nullptr; |
| 110 | |
| 111 | return D; |
| 112 | } |
| 113 | |
| 114 | if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) { |
| 115 | // C++ [temp.local]p1: |
| 116 | // Like normal (non-template) classes, class templates have an |
| 117 | // injected-class-name (Clause 9). The injected-class-name |
| 118 | // can be used with or without a template-argument-list. When |
| 119 | // it is used without a template-argument-list, it is |
| 120 | // equivalent to the injected-class-name followed by the |
| 121 | // template-parameters of the class template enclosed in |
| 122 | // <>. When it is used with a template-argument-list, it |
| 123 | // refers to the specified class template specialization, |
| 124 | // which could be the current specialization or another |
| 125 | // specialization. |
| 126 | if (Record->isInjectedClassName()) { |
| 127 | Record = cast<CXXRecordDecl>(Record->getDeclContext()); |
| 128 | if (Record->getDescribedClassTemplate()) |
| 129 | return Record->getDescribedClassTemplate(); |
| 130 | |
| 131 | if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record)) |
| 132 | return Spec->getSpecializedTemplate(); |
| 133 | } |
| 134 | |
| 135 | return nullptr; |
| 136 | } |
| 137 | |
| 138 | // 'using Dependent::foo;' can resolve to a template name. |
| 139 | // 'using typename Dependent::foo;' cannot (not even if 'foo' is an |
| 140 | // injected-class-name). |
| 141 | if (AllowDependent && isa<UnresolvedUsingValueDecl>(D)) |
| 142 | return D; |
| 143 | |
| 144 | return nullptr; |
| 145 | } |
| 146 | |
| 147 | void Sema::FilterAcceptableTemplateNames(LookupResult &R, |
| 148 | bool AllowFunctionTemplates, |
| 149 | bool AllowDependent) { |
| 150 | LookupResult::Filter filter = R.makeFilter(); |
| 151 | while (filter.hasNext()) { |
| 152 | NamedDecl *Orig = filter.next(); |
| 153 | if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent)) |
| 154 | filter.erase(); |
| 155 | } |
| 156 | filter.done(); |
| 157 | } |
| 158 | |
| 159 | bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, |
| 160 | bool AllowFunctionTemplates, |
| 161 | bool AllowDependent, |
| 162 | bool AllowNonTemplateFunctions) { |
| 163 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { |
| 164 | if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent)) |
| 165 | return true; |
| 166 | if (AllowNonTemplateFunctions && |
| 167 | isa<FunctionDecl>((*I)->getUnderlyingDecl())) |
| 168 | return true; |
| 169 | } |
| 170 | |
| 171 | return false; |
| 172 | } |
| 173 | |
| 174 | TemplateNameKind Sema::isTemplateName(Scope *S, |
| 175 | CXXScopeSpec &SS, |
| 176 | bool hasTemplateKeyword, |
| 177 | const UnqualifiedId &Name, |
| 178 | ParsedType ObjectTypePtr, |
| 179 | bool EnteringContext, |
| 180 | TemplateTy &TemplateResult, |
| 181 | bool &MemberOfUnknownSpecialization, |
| 182 | bool Disambiguation) { |
| 183 | assert(getLangOpts().CPlusPlus && "No template names in C!")(static_cast <bool> (getLangOpts().CPlusPlus && "No template names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\"" , "clang/lib/Sema/SemaTemplate.cpp", 183, __extension__ __PRETTY_FUNCTION__ )); |
| 184 | |
| 185 | DeclarationName TName; |
| 186 | MemberOfUnknownSpecialization = false; |
| 187 | |
| 188 | switch (Name.getKind()) { |
| 189 | case UnqualifiedIdKind::IK_Identifier: |
| 190 | TName = DeclarationName(Name.Identifier); |
| 191 | break; |
| 192 | |
| 193 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
| 194 | TName = Context.DeclarationNames.getCXXOperatorName( |
| 195 | Name.OperatorFunctionId.Operator); |
| 196 | break; |
| 197 | |
| 198 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
| 199 | TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); |
| 200 | break; |
| 201 | |
| 202 | default: |
| 203 | return TNK_Non_template; |
| 204 | } |
| 205 | |
| 206 | QualType ObjectType = ObjectTypePtr.get(); |
| 207 | |
| 208 | AssumedTemplateKind AssumedTemplate; |
| 209 | LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName); |
| 210 | if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext, |
| 211 | MemberOfUnknownSpecialization, SourceLocation(), |
| 212 | &AssumedTemplate, |
| 213 | /*AllowTypoCorrection=*/!Disambiguation)) |
| 214 | return TNK_Non_template; |
| 215 | |
| 216 | if (AssumedTemplate != AssumedTemplateKind::None) { |
| 217 | TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName)); |
| 218 | // Let the parser know whether we found nothing or found functions; if we |
| 219 | // found nothing, we want to more carefully check whether this is actually |
| 220 | // a function template name versus some other kind of undeclared identifier. |
| 221 | return AssumedTemplate == AssumedTemplateKind::FoundNothing |
| 222 | ? TNK_Undeclared_template |
| 223 | : TNK_Function_template; |
| 224 | } |
| 225 | |
| 226 | if (R.empty()) |
| 227 | return TNK_Non_template; |
| 228 | |
| 229 | NamedDecl *D = nullptr; |
| 230 | UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin()); |
| 231 | if (R.isAmbiguous()) { |
| 232 | // If we got an ambiguity involving a non-function template, treat this |
| 233 | // as a template name, and pick an arbitrary template for error recovery. |
| 234 | bool AnyFunctionTemplates = false; |
| 235 | for (NamedDecl *FoundD : R) { |
| 236 | if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) { |
| 237 | if (isa<FunctionTemplateDecl>(FoundTemplate)) |
| 238 | AnyFunctionTemplates = true; |
| 239 | else { |
| 240 | D = FoundTemplate; |
| 241 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD); |
| 242 | break; |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | // If we didn't find any templates at all, this isn't a template name. |
| 248 | // Leave the ambiguity for a later lookup to diagnose. |
| 249 | if (!D && !AnyFunctionTemplates) { |
| 250 | R.suppressDiagnostics(); |
| 251 | return TNK_Non_template; |
| 252 | } |
| 253 | |
| 254 | // If the only templates were function templates, filter out the rest. |
| 255 | // We'll diagnose the ambiguity later. |
| 256 | if (!D) |
| 257 | FilterAcceptableTemplateNames(R); |
| 258 | } |
| 259 | |
| 260 | // At this point, we have either picked a single template name declaration D |
| 261 | // or we have a non-empty set of results R containing either one template name |
| 262 | // declaration or a set of function templates. |
| 263 | |
| 264 | TemplateName Template; |
| 265 | TemplateNameKind TemplateKind; |
| 266 | |
| 267 | unsigned ResultCount = R.end() - R.begin(); |
| 268 | if (!D && ResultCount > 1) { |
| 269 | // We assume that we'll preserve the qualifier from a function |
| 270 | // template name in other ways. |
| 271 | Template = Context.getOverloadedTemplateName(R.begin(), R.end()); |
| 272 | TemplateKind = TNK_Function_template; |
| 273 | |
| 274 | // We'll do this lookup again later. |
| 275 | R.suppressDiagnostics(); |
| 276 | } else { |
| 277 | if (!D) { |
| 278 | D = getAsTemplateNameDecl(*R.begin()); |
| 279 | assert(D && "unambiguous result is not a template name")(static_cast <bool> (D && "unambiguous result is not a template name" ) ? void (0) : __assert_fail ("D && \"unambiguous result is not a template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 279, __extension__ __PRETTY_FUNCTION__ )); |
| 280 | } |
| 281 | |
| 282 | if (isa<UnresolvedUsingValueDecl>(D)) { |
| 283 | // We don't yet know whether this is a template-name or not. |
| 284 | MemberOfUnknownSpecialization = true; |
| 285 | return TNK_Non_template; |
| 286 | } |
| 287 | |
| 288 | TemplateDecl *TD = cast<TemplateDecl>(D); |
| 289 | Template = |
| 290 | FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); |
| 291 | assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD)(static_cast <bool> (!FoundUsingShadow || FoundUsingShadow ->getTargetDecl() == TD) ? void (0) : __assert_fail ("!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD" , "clang/lib/Sema/SemaTemplate.cpp", 291, __extension__ __PRETTY_FUNCTION__ )); |
| 292 | if (SS.isSet() && !SS.isInvalid()) { |
| 293 | NestedNameSpecifier *Qualifier = SS.getScopeRep(); |
| 294 | Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword, |
| 295 | Template); |
| 296 | } |
| 297 | |
| 298 | if (isa<FunctionTemplateDecl>(TD)) { |
| 299 | TemplateKind = TNK_Function_template; |
| 300 | |
| 301 | // We'll do this lookup again later. |
| 302 | R.suppressDiagnostics(); |
| 303 | } else { |
| 304 | assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl >(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl >(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)" , "clang/lib/Sema/SemaTemplate.cpp", 306, __extension__ __PRETTY_FUNCTION__ )) |
| 305 | isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl >(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl >(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)" , "clang/lib/Sema/SemaTemplate.cpp", 306, __extension__ __PRETTY_FUNCTION__ )) |
| 306 | isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD))(static_cast <bool> (isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl >(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl >(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)" , "clang/lib/Sema/SemaTemplate.cpp", 306, __extension__ __PRETTY_FUNCTION__ )); |
| 307 | TemplateKind = |
| 308 | isa<VarTemplateDecl>(TD) ? TNK_Var_template : |
| 309 | isa<ConceptDecl>(TD) ? TNK_Concept_template : |
| 310 | TNK_Type_template; |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | TemplateResult = TemplateTy::make(Template); |
| 315 | return TemplateKind; |
| 316 | } |
| 317 | |
| 318 | bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name, |
| 319 | SourceLocation NameLoc, CXXScopeSpec &SS, |
| 320 | ParsedTemplateTy *Template /*=nullptr*/) { |
| 321 | bool MemberOfUnknownSpecialization = false; |
| 322 | |
| 323 | // We could use redeclaration lookup here, but we don't need to: the |
| 324 | // syntactic form of a deduction guide is enough to identify it even |
| 325 | // if we can't look up the template name at all. |
| 326 | LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName); |
| 327 | if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(), |
| 328 | /*EnteringContext*/ false, |
| 329 | MemberOfUnknownSpecialization)) |
| 330 | return false; |
| 331 | |
| 332 | if (R.empty()) return false; |
| 333 | if (R.isAmbiguous()) { |
| 334 | // FIXME: Diagnose an ambiguity if we find at least one template. |
| 335 | R.suppressDiagnostics(); |
| 336 | return false; |
| 337 | } |
| 338 | |
| 339 | // We only treat template-names that name type templates as valid deduction |
| 340 | // guide names. |
| 341 | TemplateDecl *TD = R.getAsSingle<TemplateDecl>(); |
| 342 | if (!TD || !getAsTypeTemplateDecl(TD)) |
| 343 | return false; |
| 344 | |
| 345 | if (Template) |
| 346 | *Template = TemplateTy::make(TemplateName(TD)); |
| 347 | return true; |
| 348 | } |
| 349 | |
| 350 | bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, |
| 351 | SourceLocation IILoc, |
| 352 | Scope *S, |
| 353 | const CXXScopeSpec *SS, |
| 354 | TemplateTy &SuggestedTemplate, |
| 355 | TemplateNameKind &SuggestedKind) { |
| 356 | // We can't recover unless there's a dependent scope specifier preceding the |
| 357 | // template name. |
| 358 | // FIXME: Typo correction? |
| 359 | if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || |
| 360 | computeDeclContext(*SS)) |
| 361 | return false; |
| 362 | |
| 363 | // The code is missing a 'template' keyword prior to the dependent template |
| 364 | // name. |
| 365 | NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); |
| 366 | Diag(IILoc, diag::err_template_kw_missing) |
| 367 | << Qualifier << II.getName() |
| 368 | << FixItHint::CreateInsertion(IILoc, "template "); |
| 369 | SuggestedTemplate |
| 370 | = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); |
| 371 | SuggestedKind = TNK_Dependent_template_name; |
| 372 | return true; |
| 373 | } |
| 374 | |
| 375 | bool Sema::LookupTemplateName(LookupResult &Found, |
| 376 | Scope *S, CXXScopeSpec &SS, |
| 377 | QualType ObjectType, |
| 378 | bool EnteringContext, |
| 379 | bool &MemberOfUnknownSpecialization, |
| 380 | RequiredTemplateKind RequiredTemplate, |
| 381 | AssumedTemplateKind *ATK, |
| 382 | bool AllowTypoCorrection) { |
| 383 | if (ATK) |
| 384 | *ATK = AssumedTemplateKind::None; |
| 385 | |
| 386 | if (SS.isInvalid()) |
| 387 | return true; |
| 388 | |
| 389 | Found.setTemplateNameLookup(true); |
| 390 | |
| 391 | // Determine where to perform name lookup |
| 392 | MemberOfUnknownSpecialization = false; |
| 393 | DeclContext *LookupCtx = nullptr; |
| 394 | bool IsDependent = false; |
| 395 | if (!ObjectType.isNull()) { |
| 396 | // This nested-name-specifier occurs in a member access expression, e.g., |
| 397 | // x->B::f, and we are looking into the type of the object. |
| 398 | assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist")(static_cast <bool> (SS.isEmpty() && "ObjectType and scope specifier cannot coexist" ) ? void (0) : __assert_fail ("SS.isEmpty() && \"ObjectType and scope specifier cannot coexist\"" , "clang/lib/Sema/SemaTemplate.cpp", 398, __extension__ __PRETTY_FUNCTION__ )); |
| 399 | LookupCtx = computeDeclContext(ObjectType); |
| 400 | IsDependent = !LookupCtx && ObjectType->isDependentType(); |
| 401 | assert((IsDependent || !ObjectType->isIncompleteType() ||(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )) |
| 402 | !ObjectType->getAs<TagType>() ||(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )) |
| 403 | ObjectType->castAs<TagType>()->isBeingDefined()) &&(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )) |
| 404 | "Caller should have completed object type")(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )); |
| 405 | |
| 406 | // Template names cannot appear inside an Objective-C class or object type |
| 407 | // or a vector type. |
| 408 | // |
| 409 | // FIXME: This is wrong. For example: |
| 410 | // |
| 411 | // template<typename T> using Vec = T __attribute__((ext_vector_type(4))); |
| 412 | // Vec<int> vi; |
| 413 | // vi.Vec<int>::~Vec<int>(); |
| 414 | // |
| 415 | // ... should be accepted but we will not treat 'Vec' as a template name |
| 416 | // here. The right thing to do would be to check if the name is a valid |
| 417 | // vector component name, and look up a template name if not. And similarly |
| 418 | // for lookups into Objective-C class and object types, where the same |
| 419 | // problem can arise. |
| 420 | if (ObjectType->isObjCObjectOrInterfaceType() || |
| 421 | ObjectType->isVectorType()) { |
| 422 | Found.clear(); |
| 423 | return false; |
| 424 | } |
| 425 | } else if (SS.isNotEmpty()) { |
| 426 | // This nested-name-specifier occurs after another nested-name-specifier, |
| 427 | // so long into the context associated with the prior nested-name-specifier. |
| 428 | LookupCtx = computeDeclContext(SS, EnteringContext); |
| 429 | IsDependent = !LookupCtx && isDependentScopeSpecifier(SS); |
| 430 | |
| 431 | // The declaration context must be complete. |
| 432 | if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) |
| 433 | return true; |
| 434 | } |
| 435 | |
| 436 | bool ObjectTypeSearchedInScope = false; |
| 437 | bool AllowFunctionTemplatesInLookup = true; |
| 438 | if (LookupCtx) { |
| 439 | // Perform "qualified" name lookup into the declaration context we |
| 440 | // computed, which is either the type of the base of a member access |
| 441 | // expression or the declaration context associated with a prior |
| 442 | // nested-name-specifier. |
| 443 | LookupQualifiedName(Found, LookupCtx); |
| 444 | |
| 445 | // FIXME: The C++ standard does not clearly specify what happens in the |
| 446 | // case where the object type is dependent, and implementations vary. In |
| 447 | // Clang, we treat a name after a . or -> as a template-name if lookup |
| 448 | // finds a non-dependent member or member of the current instantiation that |
| 449 | // is a type template, or finds no such members and lookup in the context |
| 450 | // of the postfix-expression finds a type template. In the latter case, the |
| 451 | // name is nonetheless dependent, and we may resolve it to a member of an |
| 452 | // unknown specialization when we come to instantiate the template. |
| 453 | IsDependent |= Found.wasNotFoundInCurrentInstantiation(); |
| 454 | } |
| 455 | |
| 456 | if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) { |
| 457 | // C++ [basic.lookup.classref]p1: |
| 458 | // In a class member access expression (5.2.5), if the . or -> token is |
| 459 | // immediately followed by an identifier followed by a <, the |
| 460 | // identifier must be looked up to determine whether the < is the |
| 461 | // beginning of a template argument list (14.2) or a less-than operator. |
| 462 | // The identifier is first looked up in the class of the object |
| 463 | // expression. If the identifier is not found, it is then looked up in |
| 464 | // the context of the entire postfix-expression and shall name a class |
| 465 | // template. |
| 466 | if (S) |
| 467 | LookupName(Found, S); |
| 468 | |
| 469 | if (!ObjectType.isNull()) { |
| 470 | // FIXME: We should filter out all non-type templates here, particularly |
| 471 | // variable templates and concepts. But the exclusion of alias templates |
| 472 | // and template template parameters is a wording defect. |
| 473 | AllowFunctionTemplatesInLookup = false; |
| 474 | ObjectTypeSearchedInScope = true; |
| 475 | } |
| 476 | |
| 477 | IsDependent |= Found.wasNotFoundInCurrentInstantiation(); |
| 478 | } |
| 479 | |
| 480 | if (Found.isAmbiguous()) |
| 481 | return false; |
| 482 | |
| 483 | if (ATK && SS.isEmpty() && ObjectType.isNull() && |
| 484 | !RequiredTemplate.hasTemplateKeyword()) { |
| 485 | // C++2a [temp.names]p2: |
| 486 | // A name is also considered to refer to a template if it is an |
| 487 | // unqualified-id followed by a < and name lookup finds either one or more |
| 488 | // functions or finds nothing. |
| 489 | // |
| 490 | // To keep our behavior consistent, we apply the "finds nothing" part in |
| 491 | // all language modes, and diagnose the empty lookup in ActOnCallExpr if we |
| 492 | // successfully form a call to an undeclared template-id. |
| 493 | bool AllFunctions = |
| 494 | getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) { |
| 495 | return isa<FunctionDecl>(ND->getUnderlyingDecl()); |
| 496 | }); |
| 497 | if (AllFunctions || (Found.empty() && !IsDependent)) { |
| 498 | // If lookup found any functions, or if this is a name that can only be |
| 499 | // used for a function, then strongly assume this is a function |
| 500 | // template-id. |
| 501 | *ATK = (Found.empty() && Found.getLookupName().isIdentifier()) |
| 502 | ? AssumedTemplateKind::FoundNothing |
| 503 | : AssumedTemplateKind::FoundFunctions; |
| 504 | Found.clear(); |
| 505 | return false; |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | if (Found.empty() && !IsDependent && AllowTypoCorrection) { |
| 510 | // If we did not find any names, and this is not a disambiguation, attempt |
| 511 | // to correct any typos. |
| 512 | DeclarationName Name = Found.getLookupName(); |
| 513 | Found.clear(); |
| 514 | // Simple filter callback that, for keywords, only accepts the C++ *_cast |
| 515 | DefaultFilterCCC FilterCCC{}; |
| 516 | FilterCCC.WantTypeSpecifiers = false; |
| 517 | FilterCCC.WantExpressionKeywords = false; |
| 518 | FilterCCC.WantRemainingKeywords = false; |
| 519 | FilterCCC.WantCXXNamedCasts = true; |
| 520 | if (TypoCorrection Corrected = |
| 521 | CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S, |
| 522 | &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) { |
| 523 | if (auto *ND = Corrected.getFoundDecl()) |
| 524 | Found.addDecl(ND); |
| 525 | FilterAcceptableTemplateNames(Found); |
| 526 | if (Found.isAmbiguous()) { |
| 527 | Found.clear(); |
| 528 | } else if (!Found.empty()) { |
| 529 | Found.setLookupName(Corrected.getCorrection()); |
| 530 | if (LookupCtx) { |
| 531 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
| 532 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
| 533 | Name.getAsString() == CorrectedStr; |
| 534 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) |
| 535 | << Name << LookupCtx << DroppedSpecifier |
| 536 | << SS.getRange()); |
| 537 | } else { |
| 538 | diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); |
| 539 | } |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | NamedDecl *ExampleLookupResult = |
| 545 | Found.empty() ? nullptr : Found.getRepresentativeDecl(); |
| 546 | FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); |
| 547 | if (Found.empty()) { |
| 548 | if (IsDependent) { |
| 549 | MemberOfUnknownSpecialization = true; |
| 550 | return false; |
| 551 | } |
| 552 | |
| 553 | // If a 'template' keyword was used, a lookup that finds only non-template |
| 554 | // names is an error. |
| 555 | if (ExampleLookupResult && RequiredTemplate) { |
| 556 | Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template) |
| 557 | << Found.getLookupName() << SS.getRange() |
| 558 | << RequiredTemplate.hasTemplateKeyword() |
| 559 | << RequiredTemplate.getTemplateKeywordLoc(); |
| 560 | Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(), |
| 561 | diag::note_template_kw_refers_to_non_template) |
| 562 | << Found.getLookupName(); |
| 563 | return true; |
| 564 | } |
| 565 | |
| 566 | return false; |
| 567 | } |
| 568 | |
| 569 | if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && |
| 570 | !getLangOpts().CPlusPlus11) { |
| 571 | // C++03 [basic.lookup.classref]p1: |
| 572 | // [...] If the lookup in the class of the object expression finds a |
| 573 | // template, the name is also looked up in the context of the entire |
| 574 | // postfix-expression and [...] |
| 575 | // |
| 576 | // Note: C++11 does not perform this second lookup. |
| 577 | LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), |
| 578 | LookupOrdinaryName); |
| 579 | FoundOuter.setTemplateNameLookup(true); |
| 580 | LookupName(FoundOuter, S); |
| 581 | // FIXME: We silently accept an ambiguous lookup here, in violation of |
| 582 | // [basic.lookup]/1. |
| 583 | FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false); |
| 584 | |
| 585 | NamedDecl *OuterTemplate; |
| 586 | if (FoundOuter.empty()) { |
| 587 | // - if the name is not found, the name found in the class of the |
| 588 | // object expression is used, otherwise |
| 589 | } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() || |
| 590 | !(OuterTemplate = |
| 591 | getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) { |
| 592 | // - if the name is found in the context of the entire |
| 593 | // postfix-expression and does not name a class template, the name |
| 594 | // found in the class of the object expression is used, otherwise |
| 595 | FoundOuter.clear(); |
| 596 | } else if (!Found.isSuppressingDiagnostics()) { |
| 597 | // - if the name found is a class template, it must refer to the same |
| 598 | // entity as the one found in the class of the object expression, |
| 599 | // otherwise the program is ill-formed. |
| 600 | if (!Found.isSingleResult() || |
| 601 | getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() != |
| 602 | OuterTemplate->getCanonicalDecl()) { |
| 603 | Diag(Found.getNameLoc(), |
| 604 | diag::ext_nested_name_member_ref_lookup_ambiguous) |
| 605 | << Found.getLookupName() |
| 606 | << ObjectType; |
| 607 | Diag(Found.getRepresentativeDecl()->getLocation(), |
| 608 | diag::note_ambig_member_ref_object_type) |
| 609 | << ObjectType; |
| 610 | Diag(FoundOuter.getFoundDecl()->getLocation(), |
| 611 | diag::note_ambig_member_ref_scope); |
| 612 | |
| 613 | // Recover by taking the template that we found in the object |
| 614 | // expression's type. |
| 615 | } |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | return false; |
| 620 | } |
| 621 | |
| 622 | void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, |
| 623 | SourceLocation Less, |
| 624 | SourceLocation Greater) { |
| 625 | if (TemplateName.isInvalid()) |
| 626 | return; |
| 627 | |
| 628 | DeclarationNameInfo NameInfo; |
| 629 | CXXScopeSpec SS; |
| 630 | LookupNameKind LookupKind; |
| 631 | |
| 632 | DeclContext *LookupCtx = nullptr; |
| 633 | NamedDecl *Found = nullptr; |
| 634 | bool MissingTemplateKeyword = false; |
| 635 | |
| 636 | // Figure out what name we looked up. |
| 637 | if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) { |
| 638 | NameInfo = DRE->getNameInfo(); |
| 639 | SS.Adopt(DRE->getQualifierLoc()); |
| 640 | LookupKind = LookupOrdinaryName; |
| 641 | Found = DRE->getFoundDecl(); |
| 642 | } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) { |
| 643 | NameInfo = ME->getMemberNameInfo(); |
| 644 | SS.Adopt(ME->getQualifierLoc()); |
| 645 | LookupKind = LookupMemberName; |
| 646 | LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl(); |
| 647 | Found = ME->getMemberDecl(); |
| 648 | } else if (auto *DSDRE = |
| 649 | dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) { |
| 650 | NameInfo = DSDRE->getNameInfo(); |
| 651 | SS.Adopt(DSDRE->getQualifierLoc()); |
| 652 | MissingTemplateKeyword = true; |
| 653 | } else if (auto *DSME = |
| 654 | dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) { |
| 655 | NameInfo = DSME->getMemberNameInfo(); |
| 656 | SS.Adopt(DSME->getQualifierLoc()); |
| 657 | MissingTemplateKeyword = true; |
| 658 | } else { |
| 659 | llvm_unreachable("unexpected kind of potential template name")::llvm::llvm_unreachable_internal("unexpected kind of potential template name" , "clang/lib/Sema/SemaTemplate.cpp", 659); |
| 660 | } |
| 661 | |
| 662 | // If this is a dependent-scope lookup, diagnose that the 'template' keyword |
| 663 | // was missing. |
| 664 | if (MissingTemplateKeyword) { |
| 665 | Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing) |
| 666 | << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater); |
| 667 | return; |
| 668 | } |
| 669 | |
| 670 | // Try to correct the name by looking for templates and C++ named casts. |
| 671 | struct TemplateCandidateFilter : CorrectionCandidateCallback { |
| 672 | Sema &S; |
| 673 | TemplateCandidateFilter(Sema &S) : S(S) { |
| 674 | WantTypeSpecifiers = false; |
| 675 | WantExpressionKeywords = false; |
| 676 | WantRemainingKeywords = false; |
| 677 | WantCXXNamedCasts = true; |
| 678 | }; |
| 679 | bool ValidateCandidate(const TypoCorrection &Candidate) override { |
| 680 | if (auto *ND = Candidate.getCorrectionDecl()) |
| 681 | return S.getAsTemplateNameDecl(ND); |
| 682 | return Candidate.isKeyword(); |
| 683 | } |
| 684 | |
| 685 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
| 686 | return std::make_unique<TemplateCandidateFilter>(*this); |
| 687 | } |
| 688 | }; |
| 689 | |
| 690 | DeclarationName Name = NameInfo.getName(); |
| 691 | TemplateCandidateFilter CCC(*this); |
| 692 | if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC, |
| 693 | CTK_ErrorRecovery, LookupCtx)) { |
| 694 | auto *ND = Corrected.getFoundDecl(); |
| 695 | if (ND) |
| 696 | ND = getAsTemplateNameDecl(ND); |
| 697 | if (ND || Corrected.isKeyword()) { |
| 698 | if (LookupCtx) { |
| 699 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
| 700 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
| 701 | Name.getAsString() == CorrectedStr; |
| 702 | diagnoseTypo(Corrected, |
| 703 | PDiag(diag::err_non_template_in_member_template_id_suggest) |
| 704 | << Name << LookupCtx << DroppedSpecifier |
| 705 | << SS.getRange(), false); |
| 706 | } else { |
| 707 | diagnoseTypo(Corrected, |
| 708 | PDiag(diag::err_non_template_in_template_id_suggest) |
| 709 | << Name, false); |
| 710 | } |
| 711 | if (Found) |
| 712 | Diag(Found->getLocation(), |
| 713 | diag::note_non_template_in_template_id_found); |
| 714 | return; |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id) |
| 719 | << Name << SourceRange(Less, Greater); |
| 720 | if (Found) |
| 721 | Diag(Found->getLocation(), diag::note_non_template_in_template_id_found); |
| 722 | } |
| 723 | |
| 724 | /// ActOnDependentIdExpression - Handle a dependent id-expression that |
| 725 | /// was just parsed. This is only possible with an explicit scope |
| 726 | /// specifier naming a dependent type. |
| 727 | ExprResult |
| 728 | Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, |
| 729 | SourceLocation TemplateKWLoc, |
| 730 | const DeclarationNameInfo &NameInfo, |
| 731 | bool isAddressOfOperand, |
| 732 | const TemplateArgumentListInfo *TemplateArgs) { |
| 733 | DeclContext *DC = getFunctionLevelDeclContext(); |
| 734 | |
| 735 | // C++11 [expr.prim.general]p12: |
| 736 | // An id-expression that denotes a non-static data member or non-static |
| 737 | // member function of a class can only be used: |
| 738 | // (...) |
| 739 | // - if that id-expression denotes a non-static data member and it |
| 740 | // appears in an unevaluated operand. |
| 741 | // |
| 742 | // If this might be the case, form a DependentScopeDeclRefExpr instead of a |
| 743 | // CXXDependentScopeMemberExpr. The former can instantiate to either |
| 744 | // DeclRefExpr or MemberExpr depending on lookup results, while the latter is |
| 745 | // always a MemberExpr. |
| 746 | bool MightBeCxx11UnevalField = |
| 747 | getLangOpts().CPlusPlus11 && isUnevaluatedContext(); |
| 748 | |
| 749 | // Check if the nested name specifier is an enum type. |
| 750 | bool IsEnum = false; |
| 751 | if (NestedNameSpecifier *NNS = SS.getScopeRep()) |
| 752 | IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType()); |
| 753 | |
| 754 | if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum && |
| 755 | isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) { |
| 756 | QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(); |
| 757 | |
| 758 | // Since the 'this' expression is synthesized, we don't need to |
| 759 | // perform the double-lookup check. |
| 760 | NamedDecl *FirstQualifierInScope = nullptr; |
| 761 | |
| 762 | return CXXDependentScopeMemberExpr::Create( |
| 763 | Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true, |
| 764 | /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc, |
| 765 | FirstQualifierInScope, NameInfo, TemplateArgs); |
| 766 | } |
| 767 | |
| 768 | return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); |
| 769 | } |
| 770 | |
| 771 | ExprResult |
| 772 | Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, |
| 773 | SourceLocation TemplateKWLoc, |
| 774 | const DeclarationNameInfo &NameInfo, |
| 775 | const TemplateArgumentListInfo *TemplateArgs) { |
| 776 | // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc |
| 777 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
| 778 | if (!QualifierLoc) |
| 779 | return ExprError(); |
| 780 | |
| 781 | return DependentScopeDeclRefExpr::Create( |
| 782 | Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs); |
| 783 | } |
| 784 | |
| 785 | |
| 786 | /// Determine whether we would be unable to instantiate this template (because |
| 787 | /// it either has no definition, or is in the process of being instantiated). |
| 788 | bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, |
| 789 | NamedDecl *Instantiation, |
| 790 | bool InstantiatedFromMember, |
| 791 | const NamedDecl *Pattern, |
| 792 | const NamedDecl *PatternDef, |
| 793 | TemplateSpecializationKind TSK, |
| 794 | bool Complain /*= true*/) { |
| 795 | assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||(static_cast <bool> (isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl> (Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)" , "clang/lib/Sema/SemaTemplate.cpp", 796, __extension__ __PRETTY_FUNCTION__ )) |
| 796 | isa<VarDecl>(Instantiation))(static_cast <bool> (isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl> (Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)" , "clang/lib/Sema/SemaTemplate.cpp", 796, __extension__ __PRETTY_FUNCTION__ )); |
| 797 | |
| 798 | bool IsEntityBeingDefined = false; |
| 799 | if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef)) |
| 800 | IsEntityBeingDefined = TD->isBeingDefined(); |
| 801 | |
| 802 | if (PatternDef && !IsEntityBeingDefined) { |
| 803 | NamedDecl *SuggestedDef = nullptr; |
| 804 | if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef), |
| 805 | &SuggestedDef, |
| 806 | /*OnlyNeedComplete*/ false)) { |
| 807 | // If we're allowed to diagnose this and recover, do so. |
| 808 | bool Recover = Complain && !isSFINAEContext(); |
| 809 | if (Complain) |
| 810 | diagnoseMissingImport(PointOfInstantiation, SuggestedDef, |
| 811 | Sema::MissingImportKind::Definition, Recover); |
| 812 | return !Recover; |
| 813 | } |
| 814 | return false; |
| 815 | } |
| 816 | |
| 817 | if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) |
| 818 | return true; |
| 819 | |
| 820 | std::optional<unsigned> Note; |
| 821 | QualType InstantiationTy; |
| 822 | if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation)) |
| 823 | InstantiationTy = Context.getTypeDeclType(TD); |
| 824 | if (PatternDef) { |
| 825 | Diag(PointOfInstantiation, |
| 826 | diag::err_template_instantiate_within_definition) |
| 827 | << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation) |
| 828 | << InstantiationTy; |
| 829 | // Not much point in noting the template declaration here, since |
| 830 | // we're lexically inside it. |
| 831 | Instantiation->setInvalidDecl(); |
| 832 | } else if (InstantiatedFromMember) { |
| 833 | if (isa<FunctionDecl>(Instantiation)) { |
| 834 | Diag(PointOfInstantiation, |
| 835 | diag::err_explicit_instantiation_undefined_member) |
| 836 | << /*member function*/ 1 << Instantiation->getDeclName() |
| 837 | << Instantiation->getDeclContext(); |
| 838 | Note = diag::note_explicit_instantiation_here; |
| 839 | } else { |
| 840 | assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")(static_cast <bool> (isa<TagDecl>(Instantiation) && "Must be a TagDecl!") ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\"" , "clang/lib/Sema/SemaTemplate.cpp", 840, __extension__ __PRETTY_FUNCTION__ )); |
| 841 | Diag(PointOfInstantiation, |
| 842 | diag::err_implicit_instantiate_member_undefined) |
| 843 | << InstantiationTy; |
| 844 | Note = diag::note_member_declared_at; |
| 845 | } |
| 846 | } else { |
| 847 | if (isa<FunctionDecl>(Instantiation)) { |
| 848 | Diag(PointOfInstantiation, |
| 849 | diag::err_explicit_instantiation_undefined_func_template) |
| 850 | << Pattern; |
| 851 | Note = diag::note_explicit_instantiation_here; |
| 852 | } else if (isa<TagDecl>(Instantiation)) { |
| 853 | Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) |
| 854 | << (TSK != TSK_ImplicitInstantiation) |
| 855 | << InstantiationTy; |
| 856 | Note = diag::note_template_decl_here; |
| 857 | } else { |
| 858 | assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")(static_cast <bool> (isa<VarDecl>(Instantiation) && "Must be a VarDecl!") ? void (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\"" , "clang/lib/Sema/SemaTemplate.cpp", 858, __extension__ __PRETTY_FUNCTION__ )); |
| 859 | if (isa<VarTemplateSpecializationDecl>(Instantiation)) { |
| 860 | Diag(PointOfInstantiation, |
| 861 | diag::err_explicit_instantiation_undefined_var_template) |
| 862 | << Instantiation; |
| 863 | Instantiation->setInvalidDecl(); |
| 864 | } else |
| 865 | Diag(PointOfInstantiation, |
| 866 | diag::err_explicit_instantiation_undefined_member) |
| 867 | << /*static data member*/ 2 << Instantiation->getDeclName() |
| 868 | << Instantiation->getDeclContext(); |
| 869 | Note = diag::note_explicit_instantiation_here; |
| 870 | } |
| 871 | } |
| 872 | if (Note) // Diagnostics were emitted. |
| 873 | Diag(Pattern->getLocation(), *Note); |
| 874 | |
| 875 | // In general, Instantiation isn't marked invalid to get more than one |
| 876 | // error for multiple undefined instantiations. But the code that does |
| 877 | // explicit declaration -> explicit definition conversion can't handle |
| 878 | // invalid declarations, so mark as invalid in that case. |
| 879 | if (TSK == TSK_ExplicitInstantiationDeclaration) |
| 880 | Instantiation->setInvalidDecl(); |
| 881 | return true; |
| 882 | } |
| 883 | |
| 884 | /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining |
| 885 | /// that the template parameter 'PrevDecl' is being shadowed by a new |
| 886 | /// declaration at location Loc. Returns true to indicate that this is |
| 887 | /// an error, and false otherwise. |
| 888 | void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { |
| 889 | assert(PrevDecl->isTemplateParameter() && "Not a template parameter")(static_cast <bool> (PrevDecl->isTemplateParameter() && "Not a template parameter") ? void (0) : __assert_fail ("PrevDecl->isTemplateParameter() && \"Not a template parameter\"" , "clang/lib/Sema/SemaTemplate.cpp", 889, __extension__ __PRETTY_FUNCTION__ )); |
| 890 | |
| 891 | // C++ [temp.local]p4: |
| 892 | // A template-parameter shall not be redeclared within its |
| 893 | // scope (including nested scopes). |
| 894 | // |
| 895 | // Make this a warning when MSVC compatibility is requested. |
| 896 | unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow |
| 897 | : diag::err_template_param_shadow; |
| 898 | Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName(); |
| 899 | Diag(PrevDecl->getLocation(), diag::note_template_param_here); |
| 900 | } |
| 901 | |
| 902 | /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset |
| 903 | /// the parameter D to reference the templated declaration and return a pointer |
| 904 | /// to the template declaration. Otherwise, do nothing to D and return null. |
| 905 | TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { |
| 906 | if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { |
| 907 | D = Temp->getTemplatedDecl(); |
| 908 | return Temp; |
| 909 | } |
| 910 | return nullptr; |
| 911 | } |
| 912 | |
| 913 | ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( |
| 914 | SourceLocation EllipsisLoc) const { |
| 915 | assert(Kind == Template &&(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here" ) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\"" , "clang/lib/Sema/SemaTemplate.cpp", 916, __extension__ __PRETTY_FUNCTION__ )) |
| 916 | "Only template template arguments can be pack expansions here")(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here" ) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\"" , "clang/lib/Sema/SemaTemplate.cpp", 916, __extension__ __PRETTY_FUNCTION__ )); |
| 917 | assert(getAsTemplate().get().containsUnexpandedParameterPack() &&(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack () && "Template template argument pack expansion without packs" ) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\"" , "clang/lib/Sema/SemaTemplate.cpp", 918, __extension__ __PRETTY_FUNCTION__ )) |
| 918 | "Template template argument pack expansion without packs")(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack () && "Template template argument pack expansion without packs" ) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\"" , "clang/lib/Sema/SemaTemplate.cpp", 918, __extension__ __PRETTY_FUNCTION__ )); |
| 919 | ParsedTemplateArgument Result(*this); |
| 920 | Result.EllipsisLoc = EllipsisLoc; |
| 921 | return Result; |
| 922 | } |
| 923 | |
| 924 | static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, |
| 925 | const ParsedTemplateArgument &Arg) { |
| 926 | |
| 927 | switch (Arg.getKind()) { |
| 928 | case ParsedTemplateArgument::Type: { |
| 929 | TypeSourceInfo *DI; |
| 930 | QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); |
| 931 | if (!DI) |
| 932 | DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); |
| 933 | return TemplateArgumentLoc(TemplateArgument(T), DI); |
| 934 | } |
| 935 | |
| 936 | case ParsedTemplateArgument::NonType: { |
| 937 | Expr *E = static_cast<Expr *>(Arg.getAsExpr()); |
| 938 | return TemplateArgumentLoc(TemplateArgument(E), E); |
| 939 | } |
| 940 | |
| 941 | case ParsedTemplateArgument::Template: { |
| 942 | TemplateName Template = Arg.getAsTemplate().get(); |
| 943 | TemplateArgument TArg; |
| 944 | if (Arg.getEllipsisLoc().isValid()) |
| 945 | TArg = TemplateArgument(Template, std::optional<unsigned int>()); |
| 946 | else |
| 947 | TArg = Template; |
| 948 | return TemplateArgumentLoc( |
| 949 | SemaRef.Context, TArg, |
| 950 | Arg.getScopeSpec().getWithLocInContext(SemaRef.Context), |
| 951 | Arg.getLocation(), Arg.getEllipsisLoc()); |
| 952 | } |
| 953 | } |
| 954 | |
| 955 | llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument" , "clang/lib/Sema/SemaTemplate.cpp", 955); |
| 956 | } |
| 957 | |
| 958 | /// Translates template arguments as provided by the parser |
| 959 | /// into template arguments used by semantic analysis. |
| 960 | void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, |
| 961 | TemplateArgumentListInfo &TemplateArgs) { |
| 962 | for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) |
| 963 | TemplateArgs.addArgument(translateTemplateArgument(*this, |
| 964 | TemplateArgsIn[I])); |
| 965 | } |
| 966 | |
| 967 | static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, |
| 968 | SourceLocation Loc, |
| 969 | IdentifierInfo *Name) { |
| 970 | NamedDecl *PrevDecl = SemaRef.LookupSingleName( |
| 971 | S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); |
| 972 | if (PrevDecl && PrevDecl->isTemplateParameter()) |
| 973 | SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); |
| 974 | } |
| 975 | |
| 976 | /// Convert a parsed type into a parsed template argument. This is mostly |
| 977 | /// trivial, except that we may have parsed a C++17 deduced class template |
| 978 | /// specialization type, in which case we should form a template template |
| 979 | /// argument instead of a type template argument. |
| 980 | ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { |
| 981 | TypeSourceInfo *TInfo; |
| 982 | QualType T = GetTypeFromParser(ParsedType.get(), &TInfo); |
| 983 | if (T.isNull()) |
| 984 | return ParsedTemplateArgument(); |
| 985 | assert(TInfo && "template argument with no location")(static_cast <bool> (TInfo && "template argument with no location" ) ? void (0) : __assert_fail ("TInfo && \"template argument with no location\"" , "clang/lib/Sema/SemaTemplate.cpp", 985, __extension__ __PRETTY_FUNCTION__ )); |
| 986 | |
| 987 | // If we might have formed a deduced template specialization type, convert |
| 988 | // it to a template template argument. |
| 989 | if (getLangOpts().CPlusPlus17) { |
| 990 | TypeLoc TL = TInfo->getTypeLoc(); |
| 991 | SourceLocation EllipsisLoc; |
| 992 | if (auto PET = TL.getAs<PackExpansionTypeLoc>()) { |
| 993 | EllipsisLoc = PET.getEllipsisLoc(); |
| 994 | TL = PET.getPatternLoc(); |
| 995 | } |
| 996 | |
| 997 | CXXScopeSpec SS; |
| 998 | if (auto ET = TL.getAs<ElaboratedTypeLoc>()) { |
| 999 | SS.Adopt(ET.getQualifierLoc()); |
| 1000 | TL = ET.getNamedTypeLoc(); |
| 1001 | } |
| 1002 | |
| 1003 | if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) { |
| 1004 | TemplateName Name = DTST.getTypePtr()->getTemplateName(); |
| 1005 | if (SS.isSet()) |
| 1006 | Name = Context.getQualifiedTemplateName(SS.getScopeRep(), |
| 1007 | /*HasTemplateKeyword=*/false, |
| 1008 | Name); |
| 1009 | ParsedTemplateArgument Result(SS, TemplateTy::make(Name), |
| 1010 | DTST.getTemplateNameLoc()); |
| 1011 | if (EllipsisLoc.isValid()) |
| 1012 | Result = Result.getTemplatePackExpansion(EllipsisLoc); |
| 1013 | return Result; |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | // This is a normal type template argument. Note, if the type template |
| 1018 | // argument is an injected-class-name for a template, it has a dual nature |
| 1019 | // and can be used as either a type or a template. We handle that in |
| 1020 | // convertTypeTemplateArgumentToTemplate. |
| 1021 | return ParsedTemplateArgument(ParsedTemplateArgument::Type, |
| 1022 | ParsedType.get().getAsOpaquePtr(), |
| 1023 | TInfo->getTypeLoc().getBeginLoc()); |
| 1024 | } |
| 1025 | |
| 1026 | /// ActOnTypeParameter - Called when a C++ template type parameter |
| 1027 | /// (e.g., "typename T") has been parsed. Typename specifies whether |
| 1028 | /// the keyword "typename" was used to declare the type parameter |
| 1029 | /// (otherwise, "class" was used), and KeyLoc is the location of the |
| 1030 | /// "class" or "typename" keyword. ParamName is the name of the |
| 1031 | /// parameter (NULL indicates an unnamed template parameter) and |
| 1032 | /// ParamNameLoc is the location of the parameter name (if any). |
| 1033 | /// If the type parameter has a default argument, it will be added |
| 1034 | /// later via ActOnTypeParameterDefault. |
| 1035 | NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename, |
| 1036 | SourceLocation EllipsisLoc, |
| 1037 | SourceLocation KeyLoc, |
| 1038 | IdentifierInfo *ParamName, |
| 1039 | SourceLocation ParamNameLoc, |
| 1040 | unsigned Depth, unsigned Position, |
| 1041 | SourceLocation EqualLoc, |
| 1042 | ParsedType DefaultArg, |
| 1043 | bool HasTypeConstraint) { |
| 1044 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "Template type parameter not in template parameter scope!") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1045, __extension__ __PRETTY_FUNCTION__ )) |
| 1045 | "Template type parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() && "Template type parameter not in template parameter scope!") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1045, __extension__ __PRETTY_FUNCTION__ )); |
| 1046 | |
| 1047 | bool IsParameterPack = EllipsisLoc.isValid(); |
| 1048 | TemplateTypeParmDecl *Param |
| 1049 | = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
| 1050 | KeyLoc, ParamNameLoc, Depth, Position, |
| 1051 | ParamName, Typename, IsParameterPack, |
| 1052 | HasTypeConstraint); |
| 1053 | Param->setAccess(AS_public); |
| 1054 | |
| 1055 | if (Param->isParameterPack()) |
| 1056 | if (auto *LSI = getEnclosingLambda()) |
| 1057 | LSI->LocalPacks.push_back(Param); |
| 1058 | |
| 1059 | if (ParamName) { |
| 1060 | maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName); |
| 1061 | |
| 1062 | // Add the template parameter into the current scope. |
| 1063 | S->AddDecl(Param); |
| 1064 | IdResolver.AddDecl(Param); |
| 1065 | } |
| 1066 | |
| 1067 | // C++0x [temp.param]p9: |
| 1068 | // A default template-argument may be specified for any kind of |
| 1069 | // template-parameter that is not a template parameter pack. |
| 1070 | if (DefaultArg && IsParameterPack) { |
| 1071 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
| 1072 | DefaultArg = nullptr; |
| 1073 | } |
| 1074 | |
| 1075 | // Handle the default argument, if provided. |
| 1076 | if (DefaultArg) { |
| 1077 | TypeSourceInfo *DefaultTInfo; |
| 1078 | GetTypeFromParser(DefaultArg, &DefaultTInfo); |
| 1079 | |
| 1080 | assert(DefaultTInfo && "expected source information for type")(static_cast <bool> (DefaultTInfo && "expected source information for type" ) ? void (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\"" , "clang/lib/Sema/SemaTemplate.cpp", 1080, __extension__ __PRETTY_FUNCTION__ )); |
| 1081 | |
| 1082 | // Check for unexpanded parameter packs. |
| 1083 | if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo, |
| 1084 | UPPC_DefaultArgument)) |
| 1085 | return Param; |
| 1086 | |
| 1087 | // Check the template argument itself. |
| 1088 | if (CheckTemplateArgument(DefaultTInfo)) { |
| 1089 | Param->setInvalidDecl(); |
| 1090 | return Param; |
| 1091 | } |
| 1092 | |
| 1093 | Param->setDefaultArgument(DefaultTInfo); |
| 1094 | } |
| 1095 | |
| 1096 | return Param; |
| 1097 | } |
| 1098 | |
| 1099 | /// Convert the parser's template argument list representation into our form. |
| 1100 | static TemplateArgumentListInfo |
| 1101 | makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { |
| 1102 | TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, |
| 1103 | TemplateId.RAngleLoc); |
| 1104 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), |
| 1105 | TemplateId.NumArgs); |
| 1106 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs); |
| 1107 | return TemplateArgs; |
| 1108 | } |
| 1109 | |
| 1110 | bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) { |
| 1111 | |
| 1112 | TemplateName TN = TypeConstr->Template.get(); |
| 1113 | ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl()); |
| 1114 | |
| 1115 | // C++2a [temp.param]p4: |
| 1116 | // [...] The concept designated by a type-constraint shall be a type |
| 1117 | // concept ([temp.concept]). |
| 1118 | if (!CD->isTypeConcept()) { |
| 1119 | Diag(TypeConstr->TemplateNameLoc, |
| 1120 | diag::err_type_constraint_non_type_concept); |
| 1121 | return true; |
| 1122 | } |
| 1123 | |
| 1124 | bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid(); |
| 1125 | |
| 1126 | if (!WereArgsSpecified && |
| 1127 | CD->getTemplateParameters()->getMinRequiredArguments() > 1) { |
| 1128 | Diag(TypeConstr->TemplateNameLoc, |
| 1129 | diag::err_type_constraint_missing_arguments) |
| 1130 | << CD; |
| 1131 | return true; |
| 1132 | } |
| 1133 | return false; |
| 1134 | } |
| 1135 | |
| 1136 | bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS, |
| 1137 | TemplateIdAnnotation *TypeConstr, |
| 1138 | TemplateTypeParmDecl *ConstrainedParameter, |
| 1139 | SourceLocation EllipsisLoc) { |
| 1140 | return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc, |
| 1141 | false); |
| 1142 | } |
| 1143 | |
| 1144 | bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS, |
| 1145 | TemplateIdAnnotation *TypeConstr, |
| 1146 | TemplateTypeParmDecl *ConstrainedParameter, |
| 1147 | SourceLocation EllipsisLoc, |
| 1148 | bool AllowUnexpandedPack) { |
| 1149 | |
| 1150 | if (CheckTypeConstraint(TypeConstr)) |
| 1151 | return true; |
| 1152 | |
| 1153 | TemplateName TN = TypeConstr->Template.get(); |
| 1154 | ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl()); |
| 1155 | |
| 1156 | DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name), |
| 1157 | TypeConstr->TemplateNameLoc); |
| 1158 | |
| 1159 | TemplateArgumentListInfo TemplateArgs; |
| 1160 | if (TypeConstr->LAngleLoc.isValid()) { |
| 1161 | TemplateArgs = |
| 1162 | makeTemplateArgumentListInfo(*this, *TypeConstr); |
| 1163 | |
| 1164 | if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) { |
| 1165 | for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) { |
| 1166 | if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint)) |
| 1167 | return true; |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | return AttachTypeConstraint( |
| 1172 | SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(), |
| 1173 | ConceptName, CD, |
| 1174 | TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr, |
| 1175 | ConstrainedParameter, EllipsisLoc); |
| 1176 | } |
| 1177 | |
| 1178 | template<typename ArgumentLocAppender> |
| 1179 | static ExprResult formImmediatelyDeclaredConstraint( |
| 1180 | Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, |
| 1181 | ConceptDecl *NamedConcept, SourceLocation LAngleLoc, |
| 1182 | SourceLocation RAngleLoc, QualType ConstrainedType, |
| 1183 | SourceLocation ParamNameLoc, ArgumentLocAppender Appender, |
| 1184 | SourceLocation EllipsisLoc) { |
| 1185 | |
| 1186 | TemplateArgumentListInfo ConstraintArgs; |
| 1187 | ConstraintArgs.addArgument( |
| 1188 | S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType), |
| 1189 | /*NTTPType=*/QualType(), ParamNameLoc)); |
| 1190 | |
| 1191 | ConstraintArgs.setRAngleLoc(RAngleLoc); |
| 1192 | ConstraintArgs.setLAngleLoc(LAngleLoc); |
| 1193 | Appender(ConstraintArgs); |
| 1194 | |
| 1195 | // C++2a [temp.param]p4: |
| 1196 | // [...] This constraint-expression E is called the immediately-declared |
| 1197 | // constraint of T. [...] |
| 1198 | CXXScopeSpec SS; |
| 1199 | SS.Adopt(NS); |
| 1200 | ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId( |
| 1201 | SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo, |
| 1202 | /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs); |
| 1203 | if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid()) |
| 1204 | return ImmediatelyDeclaredConstraint; |
| 1205 | |
| 1206 | // C++2a [temp.param]p4: |
| 1207 | // [...] If T is not a pack, then E is E', otherwise E is (E' && ...). |
| 1208 | // |
| 1209 | // We have the following case: |
| 1210 | // |
| 1211 | // template<typename T> concept C1 = true; |
| 1212 | // template<C1... T> struct s1; |
| 1213 | // |
| 1214 | // The constraint: (C1<T> && ...) |
| 1215 | // |
| 1216 | // Note that the type of C1<T> is known to be 'bool', so we don't need to do |
| 1217 | // any unqualified lookups for 'operator&&' here. |
| 1218 | return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr, |
| 1219 | /*LParenLoc=*/SourceLocation(), |
| 1220 | ImmediatelyDeclaredConstraint.get(), BO_LAnd, |
| 1221 | EllipsisLoc, /*RHS=*/nullptr, |
| 1222 | /*RParenLoc=*/SourceLocation(), |
| 1223 | /*NumExpansions=*/std::nullopt); |
| 1224 | } |
| 1225 | |
| 1226 | /// Attach a type-constraint to a template parameter. |
| 1227 | /// \returns true if an error occurred. This can happen if the |
| 1228 | /// immediately-declared constraint could not be formed (e.g. incorrect number |
| 1229 | /// of arguments for the named concept). |
| 1230 | bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS, |
| 1231 | DeclarationNameInfo NameInfo, |
| 1232 | ConceptDecl *NamedConcept, |
| 1233 | const TemplateArgumentListInfo *TemplateArgs, |
| 1234 | TemplateTypeParmDecl *ConstrainedParameter, |
| 1235 | SourceLocation EllipsisLoc) { |
| 1236 | // C++2a [temp.param]p4: |
| 1237 | // [...] If Q is of the form C<A1, ..., An>, then let E' be |
| 1238 | // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...] |
| 1239 | const ASTTemplateArgumentListInfo *ArgsAsWritten = |
| 1240 | TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context, |
| 1241 | *TemplateArgs) : nullptr; |
| 1242 | |
| 1243 | QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0); |
| 1244 | |
| 1245 | ExprResult ImmediatelyDeclaredConstraint = |
| 1246 | formImmediatelyDeclaredConstraint( |
| 1247 | *this, NS, NameInfo, NamedConcept, |
| 1248 | TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(), |
| 1249 | TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(), |
| 1250 | ParamAsArgument, ConstrainedParameter->getLocation(), |
| 1251 | [&] (TemplateArgumentListInfo &ConstraintArgs) { |
| 1252 | if (TemplateArgs) |
| 1253 | for (const auto &ArgLoc : TemplateArgs->arguments()) |
| 1254 | ConstraintArgs.addArgument(ArgLoc); |
| 1255 | }, EllipsisLoc); |
| 1256 | if (ImmediatelyDeclaredConstraint.isInvalid()) |
| 1257 | return true; |
| 1258 | |
| 1259 | ConstrainedParameter->setTypeConstraint(NS, NameInfo, |
| 1260 | /*FoundDecl=*/NamedConcept, |
| 1261 | NamedConcept, ArgsAsWritten, |
| 1262 | ImmediatelyDeclaredConstraint.get()); |
| 1263 | return false; |
| 1264 | } |
| 1265 | |
| 1266 | bool Sema::AttachTypeConstraint(AutoTypeLoc TL, |
| 1267 | NonTypeTemplateParmDecl *NewConstrainedParm, |
| 1268 | NonTypeTemplateParmDecl *OrigConstrainedParm, |
| 1269 | SourceLocation EllipsisLoc) { |
| 1270 | if (NewConstrainedParm->getType() != TL.getType() || |
| 1271 | TL.getAutoKeyword() != AutoTypeKeyword::Auto) { |
| 1272 | Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), |
| 1273 | diag::err_unsupported_placeholder_constraint) |
| 1274 | << NewConstrainedParm->getTypeSourceInfo() |
| 1275 | ->getTypeLoc() |
| 1276 | .getSourceRange(); |
| 1277 | return true; |
| 1278 | } |
| 1279 | // FIXME: Concepts: This should be the type of the placeholder, but this is |
| 1280 | // unclear in the wording right now. |
| 1281 | DeclRefExpr *Ref = |
| 1282 | BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(), |
| 1283 | VK_PRValue, OrigConstrainedParm->getLocation()); |
| 1284 | if (!Ref) |
| 1285 | return true; |
| 1286 | ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint( |
| 1287 | *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(), |
| 1288 | TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(), |
| 1289 | BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(), |
| 1290 | [&](TemplateArgumentListInfo &ConstraintArgs) { |
| 1291 | for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I) |
| 1292 | ConstraintArgs.addArgument(TL.getArgLoc(I)); |
| 1293 | }, |
| 1294 | EllipsisLoc); |
| 1295 | if (ImmediatelyDeclaredConstraint.isInvalid() || |
| 1296 | !ImmediatelyDeclaredConstraint.isUsable()) |
| 1297 | return true; |
| 1298 | |
| 1299 | NewConstrainedParm->setPlaceholderTypeConstraint( |
| 1300 | ImmediatelyDeclaredConstraint.get()); |
| 1301 | return false; |
| 1302 | } |
| 1303 | |
| 1304 | /// Check that the type of a non-type template parameter is |
| 1305 | /// well-formed. |
| 1306 | /// |
| 1307 | /// \returns the (possibly-promoted) parameter type if valid; |
| 1308 | /// otherwise, produces a diagnostic and returns a NULL type. |
| 1309 | QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, |
| 1310 | SourceLocation Loc) { |
| 1311 | if (TSI->getType()->isUndeducedType()) { |
| 1312 | // C++17 [temp.dep.expr]p3: |
| 1313 | // An id-expression is type-dependent if it contains |
| 1314 | // - an identifier associated by name lookup with a non-type |
| 1315 | // template-parameter declared with a type that contains a |
| 1316 | // placeholder type (7.1.7.4), |
| 1317 | TSI = SubstAutoTypeSourceInfoDependent(TSI); |
| 1318 | } |
| 1319 | |
| 1320 | return CheckNonTypeTemplateParameterType(TSI->getType(), Loc); |
| 1321 | } |
| 1322 | |
| 1323 | /// Require the given type to be a structural type, and diagnose if it is not. |
| 1324 | /// |
| 1325 | /// \return \c true if an error was produced. |
| 1326 | bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) { |
| 1327 | if (T->isDependentType()) |
| 1328 | return false; |
| 1329 | |
| 1330 | if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete)) |
| 1331 | return true; |
| 1332 | |
| 1333 | if (T->isStructuralType()) |
| 1334 | return false; |
| 1335 | |
| 1336 | // Structural types are required to be object types or lvalue references. |
| 1337 | if (T->isRValueReferenceType()) { |
| 1338 | Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T; |
| 1339 | return true; |
| 1340 | } |
| 1341 | |
| 1342 | // Don't mention structural types in our diagnostic prior to C++20. Also, |
| 1343 | // there's not much more we can say about non-scalar non-class types -- |
| 1344 | // because we can't see functions or arrays here, those can only be language |
| 1345 | // extensions. |
| 1346 | if (!getLangOpts().CPlusPlus20 || |
| 1347 | (!T->isScalarType() && !T->isRecordType())) { |
| 1348 | Diag(Loc, diag::err_template_nontype_parm_bad_type) << T; |
| 1349 | return true; |
| 1350 | } |
| 1351 | |
| 1352 | // Structural types are required to be literal types. |
| 1353 | if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal)) |
| 1354 | return true; |
| 1355 | |
| 1356 | Diag(Loc, diag::err_template_nontype_parm_not_structural) << T; |
| 1357 | |
| 1358 | // Drill down into the reason why the class is non-structural. |
| 1359 | while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { |
| 1360 | // All members are required to be public and non-mutable, and can't be of |
| 1361 | // rvalue reference type. Check these conditions first to prefer a "local" |
| 1362 | // reason over a more distant one. |
| 1363 | for (const FieldDecl *FD : RD->fields()) { |
| 1364 | if (FD->getAccess() != AS_public) { |
| 1365 | Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0; |
| 1366 | return true; |
| 1367 | } |
| 1368 | if (FD->isMutable()) { |
| 1369 | Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T; |
| 1370 | return true; |
| 1371 | } |
| 1372 | if (FD->getType()->isRValueReferenceType()) { |
| 1373 | Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field) |
| 1374 | << T; |
| 1375 | return true; |
| 1376 | } |
| 1377 | } |
| 1378 | |
| 1379 | // All bases are required to be public. |
| 1380 | for (const auto &BaseSpec : RD->bases()) { |
| 1381 | if (BaseSpec.getAccessSpecifier() != AS_public) { |
| 1382 | Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public) |
| 1383 | << T << 1; |
| 1384 | return true; |
| 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | // All subobjects are required to be of structural types. |
| 1389 | SourceLocation SubLoc; |
| 1390 | QualType SubType; |
| 1391 | int Kind = -1; |
| 1392 | |
| 1393 | for (const FieldDecl *FD : RD->fields()) { |
| 1394 | QualType T = Context.getBaseElementType(FD->getType()); |
| 1395 | if (!T->isStructuralType()) { |
| 1396 | SubLoc = FD->getLocation(); |
| 1397 | SubType = T; |
| 1398 | Kind = 0; |
| 1399 | break; |
| 1400 | } |
| 1401 | } |
| 1402 | |
| 1403 | if (Kind == -1) { |
| 1404 | for (const auto &BaseSpec : RD->bases()) { |
| 1405 | QualType T = BaseSpec.getType(); |
| 1406 | if (!T->isStructuralType()) { |
| 1407 | SubLoc = BaseSpec.getBaseTypeLoc(); |
| 1408 | SubType = T; |
| 1409 | Kind = 1; |
| 1410 | break; |
| 1411 | } |
| 1412 | } |
| 1413 | } |
| 1414 | |
| 1415 | assert(Kind != -1 && "couldn't find reason why type is not structural")(static_cast <bool> (Kind != -1 && "couldn't find reason why type is not structural" ) ? void (0) : __assert_fail ("Kind != -1 && \"couldn't find reason why type is not structural\"" , "clang/lib/Sema/SemaTemplate.cpp", 1415, __extension__ __PRETTY_FUNCTION__ )); |
| 1416 | Diag(SubLoc, diag::note_not_structural_subobject) |
| 1417 | << T << Kind << SubType; |
| 1418 | T = SubType; |
| 1419 | RD = T->getAsCXXRecordDecl(); |
Value stored to 'RD' is never read | |
| 1420 | } |
| 1421 | |
| 1422 | return true; |
| 1423 | } |
| 1424 | |
| 1425 | QualType Sema::CheckNonTypeTemplateParameterType(QualType T, |
| 1426 | SourceLocation Loc) { |
| 1427 | // We don't allow variably-modified types as the type of non-type template |
| 1428 | // parameters. |
| 1429 | if (T->isVariablyModifiedType()) { |
| 1430 | Diag(Loc, diag::err_variably_modified_nontype_template_param) |
| 1431 | << T; |
| 1432 | return QualType(); |
| 1433 | } |
| 1434 | |
| 1435 | // C++ [temp.param]p4: |
| 1436 | // |
| 1437 | // A non-type template-parameter shall have one of the following |
| 1438 | // (optionally cv-qualified) types: |
| 1439 | // |
| 1440 | // -- integral or enumeration type, |
| 1441 | if (T->isIntegralOrEnumerationType() || |
| 1442 | // -- pointer to object or pointer to function, |
| 1443 | T->isPointerType() || |
| 1444 | // -- lvalue reference to object or lvalue reference to function, |
| 1445 | T->isLValueReferenceType() || |
| 1446 | // -- pointer to member, |
| 1447 | T->isMemberPointerType() || |
| 1448 | // -- std::nullptr_t, or |
| 1449 | T->isNullPtrType() || |
| 1450 | // -- a type that contains a placeholder type. |
| 1451 | T->isUndeducedType()) { |
| 1452 | // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter |
| 1453 | // are ignored when determining its type. |
| 1454 | return T.getUnqualifiedType(); |
| 1455 | } |
| 1456 | |
| 1457 | // C++ [temp.param]p8: |
| 1458 | // |
| 1459 | // A non-type template-parameter of type "array of T" or |
| 1460 | // "function returning T" is adjusted to be of type "pointer to |
| 1461 | // T" or "pointer to function returning T", respectively. |
| 1462 | if (T->isArrayType() || T->isFunctionType()) |
| 1463 | return Context.getDecayedType(T); |
| 1464 | |
| 1465 | // If T is a dependent type, we can't do the check now, so we |
| 1466 | // assume that it is well-formed. Note that stripping off the |
| 1467 | // qualifiers here is not really correct if T turns out to be |
| 1468 | // an array type, but we'll recompute the type everywhere it's |
| 1469 | // used during instantiation, so that should be OK. (Using the |
| 1470 | // qualified type is equally wrong.) |
| 1471 | if (T->isDependentType()) |
| 1472 | return T.getUnqualifiedType(); |
| 1473 | |
| 1474 | // C++20 [temp.param]p6: |
| 1475 | // -- a structural type |
| 1476 | if (RequireStructuralType(T, Loc)) |
| 1477 | return QualType(); |
| 1478 | |
| 1479 | if (!getLangOpts().CPlusPlus20) { |
| 1480 | // FIXME: Consider allowing structural types as an extension in C++17. (In |
| 1481 | // earlier language modes, the template argument evaluation rules are too |
| 1482 | // inflexible.) |
| 1483 | Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T; |
| 1484 | return QualType(); |
| 1485 | } |
| 1486 | |
| 1487 | Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T; |
| 1488 | return T.getUnqualifiedType(); |
| 1489 | } |
| 1490 | |
| 1491 | NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, |
| 1492 | unsigned Depth, |
| 1493 | unsigned Position, |
| 1494 | SourceLocation EqualLoc, |
| 1495 | Expr *Default) { |
| 1496 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
| 1497 | |
| 1498 | // Check that we have valid decl-specifiers specified. |
| 1499 | auto CheckValidDeclSpecifiers = [this, &D] { |
| 1500 | // C++ [temp.param] |
| 1501 | // p1 |
| 1502 | // template-parameter: |
| 1503 | // ... |
| 1504 | // parameter-declaration |
| 1505 | // p2 |
| 1506 | // ... A storage class shall not be specified in a template-parameter |
| 1507 | // declaration. |
| 1508 | // [dcl.typedef]p1: |
| 1509 | // The typedef specifier [...] shall not be used in the decl-specifier-seq |
| 1510 | // of a parameter-declaration |
| 1511 | const DeclSpec &DS = D.getDeclSpec(); |
| 1512 | auto EmitDiag = [this](SourceLocation Loc) { |
| 1513 | Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm) |
| 1514 | << FixItHint::CreateRemoval(Loc); |
| 1515 | }; |
| 1516 | if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) |
| 1517 | EmitDiag(DS.getStorageClassSpecLoc()); |
| 1518 | |
| 1519 | if (DS.getThreadStorageClassSpec() != TSCS_unspecified) |
| 1520 | EmitDiag(DS.getThreadStorageClassSpecLoc()); |
| 1521 | |
| 1522 | // [dcl.inline]p1: |
| 1523 | // The inline specifier can be applied only to the declaration or |
| 1524 | // definition of a variable or function. |
| 1525 | |
| 1526 | if (DS.isInlineSpecified()) |
| 1527 | EmitDiag(DS.getInlineSpecLoc()); |
| 1528 | |
| 1529 | // [dcl.constexpr]p1: |
| 1530 | // The constexpr specifier shall be applied only to the definition of a |
| 1531 | // variable or variable template or the declaration of a function or |
| 1532 | // function template. |
| 1533 | |
| 1534 | if (DS.hasConstexprSpecifier()) |
| 1535 | EmitDiag(DS.getConstexprSpecLoc()); |
| 1536 | |
| 1537 | // [dcl.fct.spec]p1: |
| 1538 | // Function-specifiers can be used only in function declarations. |
| 1539 | |
| 1540 | if (DS.isVirtualSpecified()) |
| 1541 | EmitDiag(DS.getVirtualSpecLoc()); |
| 1542 | |
| 1543 | if (DS.hasExplicitSpecifier()) |
| 1544 | EmitDiag(DS.getExplicitSpecLoc()); |
| 1545 | |
| 1546 | if (DS.isNoreturnSpecified()) |
| 1547 | EmitDiag(DS.getNoreturnSpecLoc()); |
| 1548 | }; |
| 1549 | |
| 1550 | CheckValidDeclSpecifiers(); |
| 1551 | |
| 1552 | if (const auto *T = TInfo->getType()->getContainedDeducedType()) |
| 1553 | if (isa<AutoType>(T)) |
| 1554 | Diag(D.getIdentifierLoc(), |
| 1555 | diag::warn_cxx14_compat_template_nontype_parm_auto_type) |
| 1556 | << QualType(TInfo->getType()->getContainedAutoType(), 0); |
| 1557 | |
| 1558 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1559, __extension__ __PRETTY_FUNCTION__ )) |
| 1559 | "Non-type template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1559, __extension__ __PRETTY_FUNCTION__ )); |
| 1560 | bool Invalid = false; |
| 1561 | |
| 1562 | QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc()); |
| 1563 | if (T.isNull()) { |
| 1564 | T = Context.IntTy; // Recover with an 'int' type. |
| 1565 | Invalid = true; |
| 1566 | } |
| 1567 | |
| 1568 | CheckFunctionOrTemplateParamDeclarator(S, D); |
| 1569 | |
| 1570 | IdentifierInfo *ParamName = D.getIdentifier(); |
| 1571 | bool IsParameterPack = D.hasEllipsis(); |
| 1572 | NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create( |
| 1573 | Context, Context.getTranslationUnitDecl(), D.getBeginLoc(), |
| 1574 | D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack, |
| 1575 | TInfo); |
| 1576 | Param->setAccess(AS_public); |
| 1577 | |
| 1578 | if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) |
| 1579 | if (TL.isConstrained()) |
| 1580 | if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc())) |
| 1581 | Invalid = true; |
| 1582 | |
| 1583 | if (Invalid) |
| 1584 | Param->setInvalidDecl(); |
| 1585 | |
| 1586 | if (Param->isParameterPack()) |
| 1587 | if (auto *LSI = getEnclosingLambda()) |
| 1588 | LSI->LocalPacks.push_back(Param); |
| 1589 | |
| 1590 | if (ParamName) { |
| 1591 | maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(), |
| 1592 | ParamName); |
| 1593 | |
| 1594 | // Add the template parameter into the current scope. |
| 1595 | S->AddDecl(Param); |
| 1596 | IdResolver.AddDecl(Param); |
| 1597 | } |
| 1598 | |
| 1599 | // C++0x [temp.param]p9: |
| 1600 | // A default template-argument may be specified for any kind of |
| 1601 | // template-parameter that is not a template parameter pack. |
| 1602 | if (Default && IsParameterPack) { |
| 1603 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
| 1604 | Default = nullptr; |
| 1605 | } |
| 1606 | |
| 1607 | // Check the well-formedness of the default template argument, if provided. |
| 1608 | if (Default) { |
| 1609 | // Check for unexpanded parameter packs. |
| 1610 | if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) |
| 1611 | return Param; |
| 1612 | |
| 1613 | Param->setDefaultArgument(Default); |
| 1614 | } |
| 1615 | |
| 1616 | return Param; |
| 1617 | } |
| 1618 | |
| 1619 | /// ActOnTemplateTemplateParameter - Called when a C++ template template |
| 1620 | /// parameter (e.g. T in template <template \<typename> class T> class array) |
| 1621 | /// has been parsed. S is the current scope. |
| 1622 | NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S, |
| 1623 | SourceLocation TmpLoc, |
| 1624 | TemplateParameterList *Params, |
| 1625 | SourceLocation EllipsisLoc, |
| 1626 | IdentifierInfo *Name, |
| 1627 | SourceLocation NameLoc, |
| 1628 | unsigned Depth, |
| 1629 | unsigned Position, |
| 1630 | SourceLocation EqualLoc, |
| 1631 | ParsedTemplateArgument Default) { |
| 1632 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "Template template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1633, __extension__ __PRETTY_FUNCTION__ )) |
| 1633 | "Template template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() && "Template template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1633, __extension__ __PRETTY_FUNCTION__ )); |
| 1634 | |
| 1635 | // Construct the parameter object. |
| 1636 | bool IsParameterPack = EllipsisLoc.isValid(); |
| 1637 | TemplateTemplateParmDecl *Param = |
| 1638 | TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
| 1639 | NameLoc.isInvalid()? TmpLoc : NameLoc, |
| 1640 | Depth, Position, IsParameterPack, |
| 1641 | Name, Params); |
| 1642 | Param->setAccess(AS_public); |
| 1643 | |
| 1644 | if (Param->isParameterPack()) |
| 1645 | if (auto *LSI = getEnclosingLambda()) |
| 1646 | LSI->LocalPacks.push_back(Param); |
| 1647 | |
| 1648 | // If the template template parameter has a name, then link the identifier |
| 1649 | // into the scope and lookup mechanisms. |
| 1650 | if (Name) { |
| 1651 | maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name); |
| 1652 | |
| 1653 | S->AddDecl(Param); |
| 1654 | IdResolver.AddDecl(Param); |
| 1655 | } |
| 1656 | |
| 1657 | if (Params->size() == 0) { |
| 1658 | Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) |
| 1659 | << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); |
| 1660 | Param->setInvalidDecl(); |
| 1661 | } |
| 1662 | |
| 1663 | // C++0x [temp.param]p9: |
| 1664 | // A default template-argument may be specified for any kind of |
| 1665 | // template-parameter that is not a template parameter pack. |
| 1666 | if (IsParameterPack && !Default.isInvalid()) { |
| 1667 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
| 1668 | Default = ParsedTemplateArgument(); |
| 1669 | } |
| 1670 | |
| 1671 | if (!Default.isInvalid()) { |
| 1672 | // Check only that we have a template template argument. We don't want to |
| 1673 | // try to check well-formedness now, because our template template parameter |
| 1674 | // might have dependent types in its template parameters, which we wouldn't |
| 1675 | // be able to match now. |
| 1676 | // |
| 1677 | // If none of the template template parameter's template arguments mention |
| 1678 | // other template parameters, we could actually perform more checking here. |
| 1679 | // However, it isn't worth doing. |
| 1680 | TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); |
| 1681 | if (DefaultArg.getArgument().getAsTemplate().isNull()) { |
| 1682 | Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template) |
| 1683 | << DefaultArg.getSourceRange(); |
| 1684 | return Param; |
| 1685 | } |
| 1686 | |
| 1687 | // Check for unexpanded parameter packs. |
| 1688 | if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), |
| 1689 | DefaultArg.getArgument().getAsTemplate(), |
| 1690 | UPPC_DefaultArgument)) |
| 1691 | return Param; |
| 1692 | |
| 1693 | Param->setDefaultArgument(Context, DefaultArg); |
| 1694 | } |
| 1695 | |
| 1696 | return Param; |
| 1697 | } |
| 1698 | |
| 1699 | namespace { |
| 1700 | class ConstraintRefersToContainingTemplateChecker |
| 1701 | : public TreeTransform<ConstraintRefersToContainingTemplateChecker> { |
| 1702 | bool Result = false; |
| 1703 | const FunctionDecl *Friend = nullptr; |
| 1704 | unsigned TemplateDepth = 0; |
| 1705 | |
| 1706 | // Check a record-decl that we've seen to see if it is a lexical parent of the |
| 1707 | // Friend, likely because it was referred to without its template arguments. |
| 1708 | void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) { |
| 1709 | CheckingRD = CheckingRD->getMostRecentDecl(); |
| 1710 | |
| 1711 | for (const DeclContext *DC = Friend->getLexicalDeclContext(); |
| 1712 | DC && !DC->isFileContext(); DC = DC->getParent()) |
| 1713 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) |
| 1714 | if (CheckingRD == RD->getMostRecentDecl()) |
| 1715 | Result = true; |
| 1716 | } |
| 1717 | |
| 1718 | void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { |
| 1719 | assert(D->getDepth() <= TemplateDepth &&(static_cast <bool> (D->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("D->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1721, __extension__ __PRETTY_FUNCTION__ )) |
| 1720 | "Nothing should reference a value below the actual template depth, "(static_cast <bool> (D->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("D->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1721, __extension__ __PRETTY_FUNCTION__ )) |
| 1721 | "depth is likely wrong")(static_cast <bool> (D->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("D->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1721, __extension__ __PRETTY_FUNCTION__ )); |
| 1722 | if (D->getDepth() != TemplateDepth) |
| 1723 | Result = true; |
| 1724 | |
| 1725 | // Necessary because the type of the NTTP might be what refers to the parent |
| 1726 | // constriant. |
| 1727 | TransformType(D->getType()); |
| 1728 | } |
| 1729 | |
| 1730 | public: |
| 1731 | using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>; |
| 1732 | |
| 1733 | ConstraintRefersToContainingTemplateChecker(Sema &SemaRef, |
| 1734 | const FunctionDecl *Friend, |
| 1735 | unsigned TemplateDepth) |
| 1736 | : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {} |
| 1737 | bool getResult() const { return Result; } |
| 1738 | |
| 1739 | // This should be the only template parm type that we have to deal with. |
| 1740 | // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and |
| 1741 | // FunctionParmPackExpr are all partially substituted, which cannot happen |
| 1742 | // with concepts at this point in translation. |
| 1743 | using inherited::TransformTemplateTypeParmType; |
| 1744 | QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
| 1745 | TemplateTypeParmTypeLoc TL, bool) { |
| 1746 | assert(TL.getDecl()->getDepth() <= TemplateDepth &&(static_cast <bool> (TL.getDecl()->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("TL.getDecl()->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1748, __extension__ __PRETTY_FUNCTION__ )) |
| 1747 | "Nothing should reference a value below the actual template depth, "(static_cast <bool> (TL.getDecl()->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("TL.getDecl()->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1748, __extension__ __PRETTY_FUNCTION__ )) |
| 1748 | "depth is likely wrong")(static_cast <bool> (TL.getDecl()->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("TL.getDecl()->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1748, __extension__ __PRETTY_FUNCTION__ )); |
| 1749 | if (TL.getDecl()->getDepth() != TemplateDepth) |
| 1750 | Result = true; |
| 1751 | return inherited::TransformTemplateTypeParmType( |
| 1752 | TLB, TL, |
| 1753 | /*SuppressObjCLifetime=*/false); |
| 1754 | } |
| 1755 | |
| 1756 | Decl *TransformDecl(SourceLocation Loc, Decl *D) { |
| 1757 | if (!D) |
| 1758 | return D; |
| 1759 | // FIXME : This is possibly an incomplete list, but it is unclear what other |
| 1760 | // Decl kinds could be used to refer to the template parameters. This is a |
| 1761 | // best guess so far based on examples currently available, but the |
| 1762 | // unreachable should catch future instances/cases. |
| 1763 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) |
| 1764 | TransformType(TD->getUnderlyingType()); |
| 1765 | else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D)) |
| 1766 | CheckNonTypeTemplateParmDecl(NTTPD); |
| 1767 | else if (auto *VD = dyn_cast<ValueDecl>(D)) |
| 1768 | TransformType(VD->getType()); |
| 1769 | else if (auto *TD = dyn_cast<TemplateDecl>(D)) |
| 1770 | TransformTemplateParameterList(TD->getTemplateParameters()); |
| 1771 | else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) |
| 1772 | CheckIfContainingRecord(RD); |
| 1773 | else if (isa<NamedDecl>(D)) { |
| 1774 | // No direct types to visit here I believe. |
| 1775 | } else |
| 1776 | llvm_unreachable("Don't know how to handle this declaration type yet")::llvm::llvm_unreachable_internal("Don't know how to handle this declaration type yet" , "clang/lib/Sema/SemaTemplate.cpp", 1776); |
| 1777 | return D; |
| 1778 | } |
| 1779 | }; |
| 1780 | } // namespace |
| 1781 | |
| 1782 | bool Sema::ConstraintExpressionDependsOnEnclosingTemplate( |
| 1783 | const FunctionDecl *Friend, unsigned TemplateDepth, |
| 1784 | const Expr *Constraint) { |
| 1785 | assert(Friend->getFriendObjectKind() && "Only works on a friend")(static_cast <bool> (Friend->getFriendObjectKind() && "Only works on a friend") ? void (0) : __assert_fail ("Friend->getFriendObjectKind() && \"Only works on a friend\"" , "clang/lib/Sema/SemaTemplate.cpp", 1785, __extension__ __PRETTY_FUNCTION__ )); |
| 1786 | ConstraintRefersToContainingTemplateChecker Checker(*this, Friend, |
| 1787 | TemplateDepth); |
| 1788 | Checker.TransformExpr(const_cast<Expr *>(Constraint)); |
| 1789 | return Checker.getResult(); |
| 1790 | } |
| 1791 | |
| 1792 | /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally |
| 1793 | /// constrained by RequiresClause, that contains the template parameters in |
| 1794 | /// Params. |
| 1795 | TemplateParameterList * |
| 1796 | Sema::ActOnTemplateParameterList(unsigned Depth, |
| 1797 | SourceLocation ExportLoc, |
| 1798 | SourceLocation TemplateLoc, |
| 1799 | SourceLocation LAngleLoc, |
| 1800 | ArrayRef<NamedDecl *> Params, |
| 1801 | SourceLocation RAngleLoc, |
| 1802 | Expr *RequiresClause) { |
| 1803 | if (ExportLoc.isValid()) |
| 1804 | Diag(ExportLoc, diag::warn_template_export_unsupported); |
| 1805 | |
| 1806 | for (NamedDecl *P : Params) |
| 1807 | warnOnReservedIdentifier(P); |
| 1808 | |
| 1809 | return TemplateParameterList::Create( |
| 1810 | Context, TemplateLoc, LAngleLoc, |
| 1811 | llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause); |
| 1812 | } |
| 1813 | |
| 1814 | static void SetNestedNameSpecifier(Sema &S, TagDecl *T, |
| 1815 | const CXXScopeSpec &SS) { |
| 1816 | if (SS.isSet()) |
| 1817 | T->setQualifierInfo(SS.getWithLocInContext(S.Context)); |
| 1818 | } |
| 1819 | |
| 1820 | DeclResult Sema::CheckClassTemplate( |
| 1821 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
| 1822 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, |
| 1823 | const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, |
| 1824 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
| 1825 | SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, |
| 1826 | TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) { |
| 1827 | assert(TemplateParams && TemplateParams->size() > 0 &&(static_cast <bool> (TemplateParams && TemplateParams ->size() > 0 && "No template parameters") ? void (0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\"" , "clang/lib/Sema/SemaTemplate.cpp", 1828, __extension__ __PRETTY_FUNCTION__ )) |
| 1828 | "No template parameters")(static_cast <bool> (TemplateParams && TemplateParams ->size() > 0 && "No template parameters") ? void (0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\"" , "clang/lib/Sema/SemaTemplate.cpp", 1828, __extension__ __PRETTY_FUNCTION__ )); |
| 1829 | assert(TUK != TUK_Reference && "Can only declare or define class templates")(static_cast <bool> (TUK != TUK_Reference && "Can only declare or define class templates" ) ? void (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\"" , "clang/lib/Sema/SemaTemplate.cpp", 1829, __extension__ __PRETTY_FUNCTION__ )); |
| 1830 | bool Invalid = false; |
| 1831 | |
| 1832 | // Check that we can declare a template here. |
| 1833 | if (CheckTemplateDeclScope(S, TemplateParams)) |
| 1834 | return true; |
| 1835 | |
| 1836 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
| 1837 | assert(Kind != TTK_Enum && "can't build template of enumerated type")(static_cast <bool> (Kind != TTK_Enum && "can't build template of enumerated type" ) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\"" , "clang/lib/Sema/SemaTemplate.cpp", 1837, __extension__ __PRETTY_FUNCTION__ )); |
| 1838 | |
| 1839 | // There is no such thing as an unnamed class template. |
| 1840 | if (!Name) { |
| 1841 | Diag(KWLoc, diag::err_template_unnamed_class); |
| 1842 | return true; |
| 1843 | } |
| 1844 | |
| 1845 | // Find any previous declaration with this name. For a friend with no |
| 1846 | // scope explicitly specified, we only look for tag declarations (per |
| 1847 | // C++11 [basic.lookup.elab]p2). |
| 1848 | DeclContext *SemanticContext; |
| 1849 | LookupResult Previous(*this, Name, NameLoc, |
| 1850 | (SS.isEmpty() && TUK == TUK_Friend) |
| 1851 | ? LookupTagName : LookupOrdinaryName, |
| 1852 | forRedeclarationInCurContext()); |
| 1853 | if (SS.isNotEmpty() && !SS.isInvalid()) { |
| 1854 | SemanticContext = computeDeclContext(SS, true); |
| 1855 | if (!SemanticContext) { |
| 1856 | // FIXME: Horrible, horrible hack! We can't currently represent this |
| 1857 | // in the AST, and historically we have just ignored such friend |
| 1858 | // class templates, so don't complain here. |
| 1859 | Diag(NameLoc, TUK == TUK_Friend |
| 1860 | ? diag::warn_template_qualified_friend_ignored |
| 1861 | : diag::err_template_qualified_declarator_no_match) |
| 1862 | << SS.getScopeRep() << SS.getRange(); |
| 1863 | return TUK != TUK_Friend; |
| 1864 | } |
| 1865 | |
| 1866 | if (RequireCompleteDeclContext(SS, SemanticContext)) |
| 1867 | return true; |
| 1868 | |
| 1869 | // If we're adding a template to a dependent context, we may need to |
| 1870 | // rebuilding some of the types used within the template parameter list, |
| 1871 | // now that we know what the current instantiation is. |
| 1872 | if (SemanticContext->isDependentContext()) { |
| 1873 | ContextRAII SavedContext(*this, SemanticContext); |
| 1874 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) |
| 1875 | Invalid = true; |
| 1876 | } else if (TUK != TUK_Friend && TUK != TUK_Reference) |
| 1877 | diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false); |
| 1878 | |
| 1879 | LookupQualifiedName(Previous, SemanticContext); |
| 1880 | } else { |
| 1881 | SemanticContext = CurContext; |
| 1882 | |
| 1883 | // C++14 [class.mem]p14: |
| 1884 | // If T is the name of a class, then each of the following shall have a |
| 1885 | // name different from T: |
| 1886 | // -- every member template of class T |
| 1887 | if (TUK != TUK_Friend && |
| 1888 | DiagnoseClassNameShadow(SemanticContext, |
| 1889 | DeclarationNameInfo(Name, NameLoc))) |
| 1890 | return true; |
| 1891 | |
| 1892 | LookupName(Previous, S); |
| 1893 | } |
| 1894 | |
| 1895 | if (Previous.isAmbiguous()) |
| 1896 | return true; |
| 1897 | |
| 1898 | NamedDecl *PrevDecl = nullptr; |
| 1899 | if (Previous.begin() != Previous.end()) |
| 1900 | PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
| 1901 | |
| 1902 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
| 1903 | // Maybe we will complain about the shadowed template parameter. |
| 1904 | DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); |
| 1905 | // Just pretend that we didn't see the previous declaration. |
| 1906 | PrevDecl = nullptr; |
| 1907 | } |
| 1908 | |
| 1909 | // If there is a previous declaration with the same name, check |
| 1910 | // whether this is a valid redeclaration. |
| 1911 | ClassTemplateDecl *PrevClassTemplate = |
| 1912 | dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); |
| 1913 | |
| 1914 | // We may have found the injected-class-name of a class template, |
| 1915 | // class template partial specialization, or class template specialization. |
| 1916 | // In these cases, grab the template that is being defined or specialized. |
| 1917 | if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && |
| 1918 | cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { |
| 1919 | PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); |
| 1920 | PrevClassTemplate |
| 1921 | = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); |
| 1922 | if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { |
| 1923 | PrevClassTemplate |
| 1924 | = cast<ClassTemplateSpecializationDecl>(PrevDecl) |
| 1925 | ->getSpecializedTemplate(); |
| 1926 | } |
| 1927 | } |
| 1928 | |
| 1929 | if (TUK == TUK_Friend) { |
| 1930 | // C++ [namespace.memdef]p3: |
| 1931 | // [...] When looking for a prior declaration of a class or a function |
| 1932 | // declared as a friend, and when the name of the friend class or |
| 1933 | // function is neither a qualified name nor a template-id, scopes outside |
| 1934 | // the innermost enclosing namespace scope are not considered. |
| 1935 | if (!SS.isSet()) { |
| 1936 | DeclContext *OutermostContext = CurContext; |
| 1937 | while (!OutermostContext->isFileContext()) |
| 1938 | OutermostContext = OutermostContext->getLookupParent(); |
| 1939 | |
| 1940 | if (PrevDecl && |
| 1941 | (OutermostContext->Equals(PrevDecl->getDeclContext()) || |
| 1942 | OutermostContext->Encloses(PrevDecl->getDeclContext()))) { |
| 1943 | SemanticContext = PrevDecl->getDeclContext(); |
| 1944 | } else { |
| 1945 | // Declarations in outer scopes don't matter. However, the outermost |
| 1946 | // context we computed is the semantic context for our new |
| 1947 | // declaration. |
| 1948 | PrevDecl = PrevClassTemplate = nullptr; |
| 1949 | SemanticContext = OutermostContext; |
| 1950 | |
| 1951 | // Check that the chosen semantic context doesn't already contain a |
| 1952 | // declaration of this name as a non-tag type. |
| 1953 | Previous.clear(LookupOrdinaryName); |
| 1954 | DeclContext *LookupContext = SemanticContext; |
| 1955 | while (LookupContext->isTransparentContext()) |
| 1956 | LookupContext = LookupContext->getLookupParent(); |
| 1957 | LookupQualifiedName(Previous, LookupContext); |
| 1958 | |
| 1959 | if (Previous.isAmbiguous()) |
| 1960 | return true; |
| 1961 | |
| 1962 | if (Previous.begin() != Previous.end()) |
| 1963 | PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
| 1964 | } |
| 1965 | } |
| 1966 | } else if (PrevDecl && |
| 1967 | !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext, |
| 1968 | S, SS.isValid())) |
| 1969 | PrevDecl = PrevClassTemplate = nullptr; |
| 1970 | |
| 1971 | if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>( |
| 1972 | PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) { |
| 1973 | if (SS.isEmpty() && |
| 1974 | !(PrevClassTemplate && |
| 1975 | PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals( |
| 1976 | SemanticContext->getRedeclContext()))) { |
| 1977 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); |
| 1978 | Diag(Shadow->getTargetDecl()->getLocation(), |
| 1979 | diag::note_using_decl_target); |
| 1980 | Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0; |
| 1981 | // Recover by ignoring the old declaration. |
| 1982 | PrevDecl = PrevClassTemplate = nullptr; |
| 1983 | } |
| 1984 | } |
| 1985 | |
| 1986 | if (PrevClassTemplate) { |
| 1987 | // Ensure that the template parameter lists are compatible. Skip this check |
| 1988 | // for a friend in a dependent context: the template parameter list itself |
| 1989 | // could be dependent. |
| 1990 | if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
| 1991 | !TemplateParameterListsAreEqual(TemplateParams, |
| 1992 | PrevClassTemplate->getTemplateParameters(), |
| 1993 | /*Complain=*/true, |
| 1994 | TPL_TemplateMatch)) |
| 1995 | return true; |
| 1996 | |
| 1997 | // C++ [temp.class]p4: |
| 1998 | // In a redeclaration, partial specialization, explicit |
| 1999 | // specialization or explicit instantiation of a class template, |
| 2000 | // the class-key shall agree in kind with the original class |
| 2001 | // template declaration (7.1.5.3). |
| 2002 | RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); |
| 2003 | if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, |
| 2004 | TUK == TUK_Definition, KWLoc, Name)) { |
| 2005 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
| 2006 | << Name |
| 2007 | << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); |
| 2008 | Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); |
| 2009 | Kind = PrevRecordDecl->getTagKind(); |
| 2010 | } |
| 2011 | |
| 2012 | // Check for redefinition of this class template. |
| 2013 | if (TUK == TUK_Definition) { |
| 2014 | if (TagDecl *Def = PrevRecordDecl->getDefinition()) { |
| 2015 | // If we have a prior definition that is not visible, treat this as |
| 2016 | // simply making that previous definition visible. |
| 2017 | NamedDecl *Hidden = nullptr; |
| 2018 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { |
| 2019 | SkipBody->ShouldSkip = true; |
| 2020 | SkipBody->Previous = Def; |
| 2021 | auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate(); |
| 2022 | assert(Tmpl && "original definition of a class template is not a "(static_cast <bool> (Tmpl && "original definition of a class template is not a " "class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 2023, __extension__ __PRETTY_FUNCTION__ )) |
| 2023 | "class template?")(static_cast <bool> (Tmpl && "original definition of a class template is not a " "class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 2023, __extension__ __PRETTY_FUNCTION__ )); |
| 2024 | makeMergedDefinitionVisible(Hidden); |
| 2025 | makeMergedDefinitionVisible(Tmpl); |
| 2026 | } else { |
| 2027 | Diag(NameLoc, diag::err_redefinition) << Name; |
| 2028 | Diag(Def->getLocation(), diag::note_previous_definition); |
| 2029 | // FIXME: Would it make sense to try to "forget" the previous |
| 2030 | // definition, as part of error recovery? |
| 2031 | return true; |
| 2032 | } |
| 2033 | } |
| 2034 | } |
| 2035 | } else if (PrevDecl) { |
| 2036 | // C++ [temp]p5: |
| 2037 | // A class template shall not have the same name as any other |
| 2038 | // template, class, function, object, enumeration, enumerator, |
| 2039 | // namespace, or type in the same scope (3.3), except as specified |
| 2040 | // in (14.5.4). |
| 2041 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; |
| 2042 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); |
| 2043 | return true; |
| 2044 | } |
| 2045 | |
| 2046 | // Check the template parameter list of this declaration, possibly |
| 2047 | // merging in the template parameter list from the previous class |
| 2048 | // template declaration. Skip this check for a friend in a dependent |
| 2049 | // context, because the template parameter list might be dependent. |
| 2050 | if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
| 2051 | CheckTemplateParameterList( |
| 2052 | TemplateParams, |
| 2053 | PrevClassTemplate |
| 2054 | ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters() |
| 2055 | : nullptr, |
| 2056 | (SS.isSet() && SemanticContext && SemanticContext->isRecord() && |
| 2057 | SemanticContext->isDependentContext()) |
| 2058 | ? TPC_ClassTemplateMember |
| 2059 | : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate, |
| 2060 | SkipBody)) |
| 2061 | Invalid = true; |
| 2062 | |
| 2063 | if (SS.isSet()) { |
| 2064 | // If the name of the template was qualified, we must be defining the |
| 2065 | // template out-of-line. |
| 2066 | if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { |
| 2067 | Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match |
| 2068 | : diag::err_member_decl_does_not_match) |
| 2069 | << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); |
| 2070 | Invalid = true; |
| 2071 | } |
| 2072 | } |
| 2073 | |
| 2074 | // If this is a templated friend in a dependent context we should not put it |
| 2075 | // on the redecl chain. In some cases, the templated friend can be the most |
| 2076 | // recent declaration tricking the template instantiator to make substitutions |
| 2077 | // there. |
| 2078 | // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious |
| 2079 | bool ShouldAddRedecl |
| 2080 | = !(TUK == TUK_Friend && CurContext->isDependentContext()); |
| 2081 | |
| 2082 | CXXRecordDecl *NewClass = |
| 2083 | CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, |
| 2084 | PrevClassTemplate && ShouldAddRedecl ? |
| 2085 | PrevClassTemplate->getTemplatedDecl() : nullptr, |
| 2086 | /*DelayTypeCreation=*/true); |
| 2087 | SetNestedNameSpecifier(*this, NewClass, SS); |
| 2088 | if (NumOuterTemplateParamLists > 0) |
| 2089 | NewClass->setTemplateParameterListsInfo( |
| 2090 | Context, |
| 2091 | llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists)); |
| 2092 | |
| 2093 | // Add alignment attributes if necessary; these attributes are checked when |
| 2094 | // the ASTContext lays out the structure. |
| 2095 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
| 2096 | AddAlignmentAttributesForRecord(NewClass); |
| 2097 | AddMsStructLayoutForRecord(NewClass); |
| 2098 | } |
| 2099 | |
| 2100 | ClassTemplateDecl *NewTemplate |
| 2101 | = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, |
| 2102 | DeclarationName(Name), TemplateParams, |
| 2103 | NewClass); |
| 2104 | |
| 2105 | if (ShouldAddRedecl) |
| 2106 | NewTemplate->setPreviousDecl(PrevClassTemplate); |
| 2107 | |
| 2108 | NewClass->setDescribedClassTemplate(NewTemplate); |
| 2109 | |
| 2110 | if (ModulePrivateLoc.isValid()) |
| 2111 | NewTemplate->setModulePrivate(); |
| 2112 | |
| 2113 | // Build the type for the class template declaration now. |
| 2114 | QualType T = NewTemplate->getInjectedClassNameSpecialization(); |
| 2115 | T = Context.getInjectedClassNameType(NewClass, T); |
| 2116 | assert(T->isDependentType() && "Class template type is not dependent?")(static_cast <bool> (T->isDependentType() && "Class template type is not dependent?") ? void (0) : __assert_fail ("T->isDependentType() && \"Class template type is not dependent?\"" , "clang/lib/Sema/SemaTemplate.cpp", 2116, __extension__ __PRETTY_FUNCTION__ )); |
| 2117 | (void)T; |
| 2118 | |
| 2119 | // If we are providing an explicit specialization of a member that is a |
| 2120 | // class template, make a note of that. |
| 2121 | if (PrevClassTemplate && |
| 2122 | PrevClassTemplate->getInstantiatedFromMemberTemplate()) |
| 2123 | PrevClassTemplate->setMemberSpecialization(); |
| 2124 | |
| 2125 | // Set the access specifier. |
| 2126 | if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) |
| 2127 | SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); |
| 2128 | |
| 2129 | // Set the lexical context of these templates |
| 2130 | NewClass->setLexicalDeclContext(CurContext); |
| 2131 | NewTemplate->setLexicalDeclContext(CurContext); |
| 2132 | |
| 2133 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) |
| 2134 | NewClass->startDefinition(); |
| 2135 | |
| 2136 | ProcessDeclAttributeList(S, NewClass, Attr); |
| 2137 | |
| 2138 | if (PrevClassTemplate) |
| 2139 | mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); |
| 2140 | |
| 2141 | AddPushedVisibilityAttribute(NewClass); |
| 2142 | inferGslOwnerPointerAttribute(NewClass); |
| 2143 | |
| 2144 | if (TUK != TUK_Friend) { |
| 2145 | // Per C++ [basic.scope.temp]p2, skip the template parameter scopes. |
| 2146 | Scope *Outer = S; |
| 2147 | while ((Outer->getFlags() & Scope::TemplateParamScope) != 0) |
| 2148 | Outer = Outer->getParent(); |
| 2149 | PushOnScopeChains(NewTemplate, Outer); |
| 2150 | } else { |
| 2151 | if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { |
| 2152 | NewTemplate->setAccess(PrevClassTemplate->getAccess()); |
| 2153 | NewClass->setAccess(PrevClassTemplate->getAccess()); |
| 2154 | } |
| 2155 | |
| 2156 | NewTemplate->setObjectOfFriendDecl(); |
| 2157 | |
| 2158 | // Friend templates are visible in fairly strange ways. |
| 2159 | if (!CurContext->isDependentContext()) { |
| 2160 | DeclContext *DC = SemanticContext->getRedeclContext(); |
| 2161 | DC->makeDeclVisibleInContext(NewTemplate); |
| 2162 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) |
| 2163 | PushOnScopeChains(NewTemplate, EnclosingScope, |
| 2164 | /* AddToContext = */ false); |
| 2165 | } |
| 2166 | |
| 2167 | FriendDecl *Friend = FriendDecl::Create( |
| 2168 | Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc); |
| 2169 | Friend->setAccess(AS_public); |
| 2170 | CurContext->addDecl(Friend); |
| 2171 | } |
| 2172 | |
| 2173 | if (PrevClassTemplate) |
| 2174 | CheckRedeclarationInModule(NewTemplate, PrevClassTemplate); |
| 2175 | |
| 2176 | if (Invalid) { |
| 2177 | NewTemplate->setInvalidDecl(); |
| 2178 | NewClass->setInvalidDecl(); |
| 2179 | } |
| 2180 | |
| 2181 | ActOnDocumentableDecl(NewTemplate); |
| 2182 | |
| 2183 | if (SkipBody && SkipBody->ShouldSkip) |
| 2184 | return SkipBody->Previous; |
| 2185 | |
| 2186 | return NewTemplate; |
| 2187 | } |
| 2188 | |
| 2189 | namespace { |
| 2190 | /// Tree transform to "extract" a transformed type from a class template's |
| 2191 | /// constructor to a deduction guide. |
| 2192 | class ExtractTypeForDeductionGuide |
| 2193 | : public TreeTransform<ExtractTypeForDeductionGuide> { |
| 2194 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs; |
| 2195 | |
| 2196 | public: |
| 2197 | typedef TreeTransform<ExtractTypeForDeductionGuide> Base; |
| 2198 | ExtractTypeForDeductionGuide( |
| 2199 | Sema &SemaRef, |
| 2200 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) |
| 2201 | : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} |
| 2202 | |
| 2203 | TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } |
| 2204 | |
| 2205 | QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { |
| 2206 | ASTContext &Context = SemaRef.getASTContext(); |
| 2207 | TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl(); |
| 2208 | TypedefNameDecl *Decl = OrigDecl; |
| 2209 | // Transform the underlying type of the typedef and clone the Decl only if |
| 2210 | // the typedef has a dependent context. |
| 2211 | if (OrigDecl->getDeclContext()->isDependentContext()) { |
| 2212 | TypeLocBuilder InnerTLB; |
| 2213 | QualType Transformed = |
| 2214 | TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc()); |
| 2215 | TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed); |
| 2216 | if (isa<TypeAliasDecl>(OrigDecl)) |
| 2217 | Decl = TypeAliasDecl::Create( |
| 2218 | Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), |
| 2219 | OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); |
| 2220 | else { |
| 2221 | assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef")(static_cast <bool> (isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef") ? void (0) : __assert_fail ("isa<TypedefDecl>(OrigDecl) && \"Not a Type alias or typedef\"" , "clang/lib/Sema/SemaTemplate.cpp", 2221, __extension__ __PRETTY_FUNCTION__ )); |
| 2222 | Decl = TypedefDecl::Create( |
| 2223 | Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), |
| 2224 | OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); |
| 2225 | } |
| 2226 | MaterializedTypedefs.push_back(Decl); |
| 2227 | } |
| 2228 | |
| 2229 | QualType TDTy = Context.getTypedefType(Decl); |
| 2230 | TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy); |
| 2231 | TypedefTL.setNameLoc(TL.getNameLoc()); |
| 2232 | |
| 2233 | return TDTy; |
| 2234 | } |
| 2235 | }; |
| 2236 | |
| 2237 | /// Transform to convert portions of a constructor declaration into the |
| 2238 | /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. |
| 2239 | struct ConvertConstructorToDeductionGuideTransform { |
| 2240 | ConvertConstructorToDeductionGuideTransform(Sema &S, |
| 2241 | ClassTemplateDecl *Template) |
| 2242 | : SemaRef(S), Template(Template) {} |
| 2243 | |
| 2244 | Sema &SemaRef; |
| 2245 | ClassTemplateDecl *Template; |
| 2246 | |
| 2247 | DeclContext *DC = Template->getDeclContext(); |
| 2248 | CXXRecordDecl *Primary = Template->getTemplatedDecl(); |
| 2249 | DeclarationName DeductionGuideName = |
| 2250 | SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template); |
| 2251 | |
| 2252 | QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary); |
| 2253 | |
| 2254 | // Index adjustment to apply to convert depth-1 template parameters into |
| 2255 | // depth-0 template parameters. |
| 2256 | unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size(); |
| 2257 | |
| 2258 | /// Transform a constructor declaration into a deduction guide. |
| 2259 | NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, |
| 2260 | CXXConstructorDecl *CD) { |
| 2261 | SmallVector<TemplateArgument, 16> SubstArgs; |
| 2262 | |
| 2263 | LocalInstantiationScope Scope(SemaRef); |
| 2264 | |
| 2265 | // C++ [over.match.class.deduct]p1: |
| 2266 | // -- For each constructor of the class template designated by the |
| 2267 | // template-name, a function template with the following properties: |
| 2268 | |
| 2269 | // -- The template parameters are the template parameters of the class |
| 2270 | // template followed by the template parameters (including default |
| 2271 | // template arguments) of the constructor, if any. |
| 2272 | TemplateParameterList *TemplateParams = Template->getTemplateParameters(); |
| 2273 | if (FTD) { |
| 2274 | TemplateParameterList *InnerParams = FTD->getTemplateParameters(); |
| 2275 | SmallVector<NamedDecl *, 16> AllParams; |
| 2276 | AllParams.reserve(TemplateParams->size() + InnerParams->size()); |
| 2277 | AllParams.insert(AllParams.begin(), |
| 2278 | TemplateParams->begin(), TemplateParams->end()); |
| 2279 | SubstArgs.reserve(InnerParams->size()); |
| 2280 | |
| 2281 | // Later template parameters could refer to earlier ones, so build up |
| 2282 | // a list of substituted template arguments as we go. |
| 2283 | for (NamedDecl *Param : *InnerParams) { |
| 2284 | MultiLevelTemplateArgumentList Args; |
| 2285 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
| 2286 | Args.addOuterTemplateArguments(SubstArgs); |
| 2287 | Args.addOuterRetainedLevel(); |
| 2288 | NamedDecl *NewParam = transformTemplateParameter(Param, Args); |
| 2289 | if (!NewParam) |
| 2290 | return nullptr; |
| 2291 | AllParams.push_back(NewParam); |
| 2292 | SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument( |
| 2293 | SemaRef.Context.getInjectedTemplateArg(NewParam))); |
| 2294 | } |
| 2295 | |
| 2296 | // Substitute new template parameters into requires-clause if present. |
| 2297 | Expr *RequiresClause = nullptr; |
| 2298 | if (Expr *InnerRC = InnerParams->getRequiresClause()) { |
| 2299 | MultiLevelTemplateArgumentList Args; |
| 2300 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
| 2301 | Args.addOuterTemplateArguments(SubstArgs); |
| 2302 | Args.addOuterRetainedLevel(); |
| 2303 | ExprResult E = SemaRef.SubstExpr(InnerRC, Args); |
| 2304 | if (E.isInvalid()) |
| 2305 | return nullptr; |
| 2306 | RequiresClause = E.getAs<Expr>(); |
| 2307 | } |
| 2308 | |
| 2309 | TemplateParams = TemplateParameterList::Create( |
| 2310 | SemaRef.Context, InnerParams->getTemplateLoc(), |
| 2311 | InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(), |
| 2312 | RequiresClause); |
| 2313 | } |
| 2314 | |
| 2315 | // If we built a new template-parameter-list, track that we need to |
| 2316 | // substitute references to the old parameters into references to the |
| 2317 | // new ones. |
| 2318 | MultiLevelTemplateArgumentList Args; |
| 2319 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
| 2320 | if (FTD) { |
| 2321 | Args.addOuterTemplateArguments(SubstArgs); |
| 2322 | Args.addOuterRetainedLevel(); |
| 2323 | } |
| 2324 | |
| 2325 | FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc() |
| 2326 | .getAsAdjusted<FunctionProtoTypeLoc>(); |
| 2327 | assert(FPTL && "no prototype for constructor declaration")(static_cast <bool> (FPTL && "no prototype for constructor declaration" ) ? void (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\"" , "clang/lib/Sema/SemaTemplate.cpp", 2327, __extension__ __PRETTY_FUNCTION__ )); |
| 2328 | |
| 2329 | // Transform the type of the function, adjusting the return type and |
| 2330 | // replacing references to the old parameters with references to the |
| 2331 | // new ones. |
| 2332 | TypeLocBuilder TLB; |
| 2333 | SmallVector<ParmVarDecl*, 8> Params; |
| 2334 | SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs; |
| 2335 | QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args, |
| 2336 | MaterializedTypedefs); |
| 2337 | if (NewType.isNull()) |
| 2338 | return nullptr; |
| 2339 | TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType); |
| 2340 | |
| 2341 | return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(), |
| 2342 | NewTInfo, CD->getBeginLoc(), CD->getLocation(), |
| 2343 | CD->getEndLoc(), MaterializedTypedefs); |
| 2344 | } |
| 2345 | |
| 2346 | /// Build a deduction guide with the specified parameter types. |
| 2347 | NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) { |
| 2348 | SourceLocation Loc = Template->getLocation(); |
| 2349 | |
| 2350 | // Build the requested type. |
| 2351 | FunctionProtoType::ExtProtoInfo EPI; |
| 2352 | EPI.HasTrailingReturn = true; |
| 2353 | QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc, |
| 2354 | DeductionGuideName, EPI); |
| 2355 | TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc); |
| 2356 | |
| 2357 | FunctionProtoTypeLoc FPTL = |
| 2358 | TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>(); |
| 2359 | |
| 2360 | // Build the parameters, needed during deduction / substitution. |
| 2361 | SmallVector<ParmVarDecl*, 4> Params; |
| 2362 | for (auto T : ParamTypes) { |
| 2363 | ParmVarDecl *NewParam = ParmVarDecl::Create( |
| 2364 | SemaRef.Context, DC, Loc, Loc, nullptr, T, |
| 2365 | SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr); |
| 2366 | NewParam->setScopeInfo(0, Params.size()); |
| 2367 | FPTL.setParam(Params.size(), NewParam); |
| 2368 | Params.push_back(NewParam); |
| 2369 | } |
| 2370 | |
| 2371 | return buildDeductionGuide(Template->getTemplateParameters(), nullptr, |
| 2372 | ExplicitSpecifier(), TSI, Loc, Loc, Loc); |
| 2373 | } |
| 2374 | |
| 2375 | private: |
| 2376 | /// Transform a constructor template parameter into a deduction guide template |
| 2377 | /// parameter, rebuilding any internal references to earlier parameters and |
| 2378 | /// renumbering as we go. |
| 2379 | NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam, |
| 2380 | MultiLevelTemplateArgumentList &Args) { |
| 2381 | if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) { |
| 2382 | // TemplateTypeParmDecl's index cannot be changed after creation, so |
| 2383 | // substitute it directly. |
| 2384 | auto *NewTTP = TemplateTypeParmDecl::Create( |
| 2385 | SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), |
| 2386 | /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(), |
| 2387 | TTP->getIdentifier(), TTP->wasDeclaredWithTypename(), |
| 2388 | TTP->isParameterPack(), TTP->hasTypeConstraint(), |
| 2389 | TTP->isExpandedParameterPack() |
| 2390 | ? std::optional<unsigned>(TTP->getNumExpansionParameters()) |
| 2391 | : std::nullopt); |
| 2392 | if (const auto *TC = TTP->getTypeConstraint()) |
| 2393 | SemaRef.SubstTypeConstraint(NewTTP, TC, Args, |
| 2394 | /*EvaluateConstraint*/ true); |
| 2395 | if (TTP->hasDefaultArgument()) { |
| 2396 | TypeSourceInfo *InstantiatedDefaultArg = |
| 2397 | SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args, |
| 2398 | TTP->getDefaultArgumentLoc(), TTP->getDeclName()); |
| 2399 | if (InstantiatedDefaultArg) |
| 2400 | NewTTP->setDefaultArgument(InstantiatedDefaultArg); |
| 2401 | } |
| 2402 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam, |
| 2403 | NewTTP); |
| 2404 | return NewTTP; |
| 2405 | } |
| 2406 | |
| 2407 | if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam)) |
| 2408 | return transformTemplateParameterImpl(TTP, Args); |
| 2409 | |
| 2410 | return transformTemplateParameterImpl( |
| 2411 | cast<NonTypeTemplateParmDecl>(TemplateParam), Args); |
| 2412 | } |
| 2413 | template<typename TemplateParmDecl> |
| 2414 | TemplateParmDecl * |
| 2415 | transformTemplateParameterImpl(TemplateParmDecl *OldParam, |
| 2416 | MultiLevelTemplateArgumentList &Args) { |
| 2417 | // Ask the template instantiator to do the heavy lifting for us, then adjust |
| 2418 | // the index of the parameter once it's done. |
| 2419 | auto *NewParam = |
| 2420 | cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args)); |
| 2421 | assert(NewParam->getDepth() == 0 && "unexpected template param depth")(static_cast <bool> (NewParam->getDepth() == 0 && "unexpected template param depth") ? void (0) : __assert_fail ("NewParam->getDepth() == 0 && \"unexpected template param depth\"" , "clang/lib/Sema/SemaTemplate.cpp", 2421, __extension__ __PRETTY_FUNCTION__ )); |
| 2422 | NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment); |
| 2423 | return NewParam; |
| 2424 | } |
| 2425 | |
| 2426 | QualType transformFunctionProtoType( |
| 2427 | TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, |
| 2428 | SmallVectorImpl<ParmVarDecl *> &Params, |
| 2429 | MultiLevelTemplateArgumentList &Args, |
| 2430 | SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { |
| 2431 | SmallVector<QualType, 4> ParamTypes; |
| 2432 | const FunctionProtoType *T = TL.getTypePtr(); |
| 2433 | |
| 2434 | // -- The types of the function parameters are those of the constructor. |
| 2435 | for (auto *OldParam : TL.getParams()) { |
| 2436 | ParmVarDecl *NewParam = |
| 2437 | transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs); |
| 2438 | if (!NewParam) |
| 2439 | return QualType(); |
| 2440 | ParamTypes.push_back(NewParam->getType()); |
| 2441 | Params.push_back(NewParam); |
| 2442 | } |
| 2443 | |
| 2444 | // -- The return type is the class template specialization designated by |
| 2445 | // the template-name and template arguments corresponding to the |
| 2446 | // template parameters obtained from the class template. |
| 2447 | // |
| 2448 | // We use the injected-class-name type of the primary template instead. |
| 2449 | // This has the convenient property that it is different from any type that |
| 2450 | // the user can write in a deduction-guide (because they cannot enter the |
| 2451 | // context of the template), so implicit deduction guides can never collide |
| 2452 | // with explicit ones. |
| 2453 | QualType ReturnType = DeducedType; |
| 2454 | TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation()); |
| 2455 | |
| 2456 | // Resolving a wording defect, we also inherit the variadicness of the |
| 2457 | // constructor. |
| 2458 | FunctionProtoType::ExtProtoInfo EPI; |
| 2459 | EPI.Variadic = T->isVariadic(); |
| 2460 | EPI.HasTrailingReturn = true; |
| 2461 | |
| 2462 | QualType Result = SemaRef.BuildFunctionType( |
| 2463 | ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI); |
| 2464 | if (Result.isNull()) |
| 2465 | return QualType(); |
| 2466 | |
| 2467 | FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result); |
| 2468 | NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); |
| 2469 | NewTL.setLParenLoc(TL.getLParenLoc()); |
| 2470 | NewTL.setRParenLoc(TL.getRParenLoc()); |
| 2471 | NewTL.setExceptionSpecRange(SourceRange()); |
| 2472 | NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); |
| 2473 | for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I) |
| 2474 | NewTL.setParam(I, Params[I]); |
| 2475 | |
| 2476 | return Result; |
| 2477 | } |
| 2478 | |
| 2479 | ParmVarDecl *transformFunctionTypeParam( |
| 2480 | ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args, |
| 2481 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { |
| 2482 | TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); |
| 2483 | TypeSourceInfo *NewDI; |
| 2484 | if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { |
| 2485 | // Expand out the one and only element in each inner pack. |
| 2486 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); |
| 2487 | NewDI = |
| 2488 | SemaRef.SubstType(PackTL.getPatternLoc(), Args, |
| 2489 | OldParam->getLocation(), OldParam->getDeclName()); |
| 2490 | if (!NewDI) return nullptr; |
| 2491 | NewDI = |
| 2492 | SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(), |
| 2493 | PackTL.getTypePtr()->getNumExpansions()); |
| 2494 | } else |
| 2495 | NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(), |
| 2496 | OldParam->getDeclName()); |
| 2497 | if (!NewDI) |
| 2498 | return nullptr; |
| 2499 | |
| 2500 | // Extract the type. This (for instance) replaces references to typedef |
| 2501 | // members of the current instantiations with the definitions of those |
| 2502 | // typedefs, avoiding triggering instantiation of the deduced type during |
| 2503 | // deduction. |
| 2504 | NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs) |
| 2505 | .transform(NewDI); |
| 2506 | |
| 2507 | // Resolving a wording defect, we also inherit default arguments from the |
| 2508 | // constructor. |
| 2509 | ExprResult NewDefArg; |
| 2510 | if (OldParam->hasDefaultArg()) { |
| 2511 | // We don't care what the value is (we won't use it); just create a |
| 2512 | // placeholder to indicate there is a default argument. |
| 2513 | QualType ParamTy = NewDI->getType(); |
| 2514 | NewDefArg = new (SemaRef.Context) |
| 2515 | OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(), |
| 2516 | ParamTy.getNonLValueExprType(SemaRef.Context), |
| 2517 | ParamTy->isLValueReferenceType() ? VK_LValue |
| 2518 | : ParamTy->isRValueReferenceType() ? VK_XValue |
| 2519 | : VK_PRValue); |
| 2520 | } |
| 2521 | |
| 2522 | ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC, |
| 2523 | OldParam->getInnerLocStart(), |
| 2524 | OldParam->getLocation(), |
| 2525 | OldParam->getIdentifier(), |
| 2526 | NewDI->getType(), |
| 2527 | NewDI, |
| 2528 | OldParam->getStorageClass(), |
| 2529 | NewDefArg.get()); |
| 2530 | NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(), |
| 2531 | OldParam->getFunctionScopeIndex()); |
| 2532 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); |
| 2533 | return NewParam; |
| 2534 | } |
| 2535 | |
| 2536 | FunctionTemplateDecl *buildDeductionGuide( |
| 2537 | TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor, |
| 2538 | ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart, |
| 2539 | SourceLocation Loc, SourceLocation LocEnd, |
| 2540 | llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) { |
| 2541 | DeclarationNameInfo Name(DeductionGuideName, Loc); |
| 2542 | ArrayRef<ParmVarDecl *> Params = |
| 2543 | TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(); |
| 2544 | |
| 2545 | // Build the implicit deduction guide template. |
| 2546 | auto *Guide = |
| 2547 | CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name, |
| 2548 | TInfo->getType(), TInfo, LocEnd, Ctor); |
| 2549 | Guide->setImplicit(); |
| 2550 | Guide->setParams(Params); |
| 2551 | |
| 2552 | for (auto *Param : Params) |
| 2553 | Param->setDeclContext(Guide); |
| 2554 | for (auto *TD : MaterializedTypedefs) |
| 2555 | TD->setDeclContext(Guide); |
| 2556 | |
| 2557 | auto *GuideTemplate = FunctionTemplateDecl::Create( |
| 2558 | SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide); |
| 2559 | GuideTemplate->setImplicit(); |
| 2560 | Guide->setDescribedFunctionTemplate(GuideTemplate); |
| 2561 | |
| 2562 | if (isa<CXXRecordDecl>(DC)) { |
| 2563 | Guide->setAccess(AS_public); |
| 2564 | GuideTemplate->setAccess(AS_public); |
| 2565 | } |
| 2566 | |
| 2567 | DC->addDecl(GuideTemplate); |
| 2568 | return GuideTemplate; |
| 2569 | } |
| 2570 | }; |
| 2571 | } |
| 2572 | |
| 2573 | void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template, |
| 2574 | SourceLocation Loc) { |
| 2575 | if (CXXRecordDecl *DefRecord = |
| 2576 | cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) { |
| 2577 | TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate(); |
| 2578 | Template = DescribedTemplate ? DescribedTemplate : Template; |
| 2579 | } |
| 2580 | |
| 2581 | DeclContext *DC = Template->getDeclContext(); |
| 2582 | if (DC->isDependentContext()) |
| 2583 | return; |
| 2584 | |
| 2585 | ConvertConstructorToDeductionGuideTransform Transform( |
| 2586 | *this, cast<ClassTemplateDecl>(Template)); |
| 2587 | if (!isCompleteType(Loc, Transform.DeducedType)) |
| 2588 | return; |
| 2589 | |
| 2590 | // Check whether we've already declared deduction guides for this template. |
| 2591 | // FIXME: Consider storing a flag on the template to indicate this. |
| 2592 | auto Existing = DC->lookup(Transform.DeductionGuideName); |
| 2593 | for (auto *D : Existing) |
| 2594 | if (D->isImplicit()) |
| 2595 | return; |
| 2596 | |
| 2597 | // In case we were expanding a pack when we attempted to declare deduction |
| 2598 | // guides, turn off pack expansion for everything we're about to do. |
| 2599 | ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); |
| 2600 | // Create a template instantiation record to track the "instantiation" of |
| 2601 | // constructors into deduction guides. |
| 2602 | // FIXME: Add a kind for this to give more meaningful diagnostics. But can |
| 2603 | // this substitution process actually fail? |
| 2604 | InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template); |
| 2605 | if (BuildingDeductionGuides.isInvalid()) |
| 2606 | return; |
| 2607 | |
| 2608 | // Convert declared constructors into deduction guide templates. |
| 2609 | // FIXME: Skip constructors for which deduction must necessarily fail (those |
| 2610 | // for which some class template parameter without a default argument never |
| 2611 | // appears in a deduced context). |
| 2612 | llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors; |
| 2613 | bool AddedAny = false; |
| 2614 | for (NamedDecl *D : LookupConstructors(Transform.Primary)) { |
| 2615 | D = D->getUnderlyingDecl(); |
| 2616 | if (D->isInvalidDecl() || D->isImplicit()) |
| 2617 | continue; |
| 2618 | |
| 2619 | D = cast<NamedDecl>(D->getCanonicalDecl()); |
| 2620 | |
| 2621 | // Within C++20 modules, we may have multiple same constructors in |
| 2622 | // multiple same RecordDecls. And it doesn't make sense to create |
| 2623 | // duplicated deduction guides for the duplicated constructors. |
| 2624 | if (ProcessedCtors.count(D)) |
| 2625 | continue; |
| 2626 | |
| 2627 | auto *FTD = dyn_cast<FunctionTemplateDecl>(D); |
| 2628 | auto *CD = |
| 2629 | dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D); |
| 2630 | // Class-scope explicit specializations (MS extension) do not result in |
| 2631 | // deduction guides. |
| 2632 | if (!CD || (!FTD && CD->isFunctionTemplateSpecialization())) |
| 2633 | continue; |
| 2634 | |
| 2635 | // Cannot make a deduction guide when unparsed arguments are present. |
| 2636 | if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) { |
| 2637 | return !P || P->hasUnparsedDefaultArg(); |
| 2638 | })) |
| 2639 | continue; |
| 2640 | |
| 2641 | ProcessedCtors.insert(D); |
| 2642 | Transform.transformConstructor(FTD, CD); |
| 2643 | AddedAny = true; |
| 2644 | } |
| 2645 | |
| 2646 | // C++17 [over.match.class.deduct] |
| 2647 | // -- If C is not defined or does not declare any constructors, an |
| 2648 | // additional function template derived as above from a hypothetical |
| 2649 | // constructor C(). |
| 2650 | if (!AddedAny) |
| 2651 | Transform.buildSimpleDeductionGuide(std::nullopt); |
| 2652 | |
| 2653 | // -- An additional function template derived as above from a hypothetical |
| 2654 | // constructor C(C), called the copy deduction candidate. |
| 2655 | cast<CXXDeductionGuideDecl>( |
| 2656 | cast<FunctionTemplateDecl>( |
| 2657 | Transform.buildSimpleDeductionGuide(Transform.DeducedType)) |
| 2658 | ->getTemplatedDecl()) |
| 2659 | ->setIsCopyDeductionCandidate(); |
| 2660 | } |
| 2661 | |
| 2662 | /// Diagnose the presence of a default template argument on a |
| 2663 | /// template parameter, which is ill-formed in certain contexts. |
| 2664 | /// |
| 2665 | /// \returns true if the default template argument should be dropped. |
| 2666 | static bool DiagnoseDefaultTemplateArgument(Sema &S, |
| 2667 | Sema::TemplateParamListContext TPC, |
| 2668 | SourceLocation ParamLoc, |
| 2669 | SourceRange DefArgRange) { |
| 2670 | switch (TPC) { |
| 2671 | case Sema::TPC_ClassTemplate: |
| 2672 | case Sema::TPC_VarTemplate: |
| 2673 | case Sema::TPC_TypeAliasTemplate: |
| 2674 | return false; |
| 2675 | |
| 2676 | case Sema::TPC_FunctionTemplate: |
| 2677 | case Sema::TPC_FriendFunctionTemplateDefinition: |
| 2678 | // C++ [temp.param]p9: |
| 2679 | // A default template-argument shall not be specified in a |
| 2680 | // function template declaration or a function template |
| 2681 | // definition [...] |
| 2682 | // If a friend function template declaration specifies a default |
| 2683 | // template-argument, that declaration shall be a definition and shall be |
| 2684 | // the only declaration of the function template in the translation unit. |
| 2685 | // (C++98/03 doesn't have this wording; see DR226). |
| 2686 | S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? |
| 2687 | diag::warn_cxx98_compat_template_parameter_default_in_function_template |
| 2688 | : diag::ext_template_parameter_default_in_function_template) |
| 2689 | << DefArgRange; |
| 2690 | return false; |
| 2691 | |
| 2692 | case Sema::TPC_ClassTemplateMember: |
| 2693 | // C++0x [temp.param]p9: |
| 2694 | // A default template-argument shall not be specified in the |
| 2695 | // template-parameter-lists of the definition of a member of a |
| 2696 | // class template that appears outside of the member's class. |
| 2697 | S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) |
| 2698 | << DefArgRange; |
| 2699 | return true; |
| 2700 | |
| 2701 | case Sema::TPC_FriendClassTemplate: |
| 2702 | case Sema::TPC_FriendFunctionTemplate: |
| 2703 | // C++ [temp.param]p9: |
| 2704 | // A default template-argument shall not be specified in a |
| 2705 | // friend template declaration. |
| 2706 | S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) |
| 2707 | << DefArgRange; |
| 2708 | return true; |
| 2709 | |
| 2710 | // FIXME: C++0x [temp.param]p9 allows default template-arguments |
| 2711 | // for friend function templates if there is only a single |
| 2712 | // declaration (and it is a definition). Strange! |
| 2713 | } |
| 2714 | |
| 2715 | llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!" , "clang/lib/Sema/SemaTemplate.cpp", 2715); |
| 2716 | } |
| 2717 | |
| 2718 | /// Check for unexpanded parameter packs within the template parameters |
| 2719 | /// of a template template parameter, recursively. |
| 2720 | static bool DiagnoseUnexpandedParameterPacks(Sema &S, |
| 2721 | TemplateTemplateParmDecl *TTP) { |
| 2722 | // A template template parameter which is a parameter pack is also a pack |
| 2723 | // expansion. |
| 2724 | if (TTP->isParameterPack()) |
| 2725 | return false; |
| 2726 | |
| 2727 | TemplateParameterList *Params = TTP->getTemplateParameters(); |
| 2728 | for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
| 2729 | NamedDecl *P = Params->getParam(I); |
| 2730 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) { |
| 2731 | if (!TTP->isParameterPack()) |
| 2732 | if (const TypeConstraint *TC = TTP->getTypeConstraint()) |
| 2733 | if (TC->hasExplicitTemplateArgs()) |
| 2734 | for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) |
| 2735 | if (S.DiagnoseUnexpandedParameterPack(ArgLoc, |
| 2736 | Sema::UPPC_TypeConstraint)) |
| 2737 | return true; |
| 2738 | continue; |
| 2739 | } |
| 2740 | |
| 2741 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { |
| 2742 | if (!NTTP->isParameterPack() && |
| 2743 | S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), |
| 2744 | NTTP->getTypeSourceInfo(), |
| 2745 | Sema::UPPC_NonTypeTemplateParameterType)) |
| 2746 | return true; |
| 2747 | |
| 2748 | continue; |
| 2749 | } |
| 2750 | |
| 2751 | if (TemplateTemplateParmDecl *InnerTTP |
| 2752 | = dyn_cast<TemplateTemplateParmDecl>(P)) |
| 2753 | if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) |
| 2754 | return true; |
| 2755 | } |
| 2756 | |
| 2757 | return false; |
| 2758 | } |
| 2759 | |
| 2760 | /// Checks the validity of a template parameter list, possibly |
| 2761 | /// considering the template parameter list from a previous |
| 2762 | /// declaration. |
| 2763 | /// |
| 2764 | /// If an "old" template parameter list is provided, it must be |
| 2765 | /// equivalent (per TemplateParameterListsAreEqual) to the "new" |
| 2766 | /// template parameter list. |
| 2767 | /// |
| 2768 | /// \param NewParams Template parameter list for a new template |
| 2769 | /// declaration. This template parameter list will be updated with any |
| 2770 | /// default arguments that are carried through from the previous |
| 2771 | /// template parameter list. |
| 2772 | /// |
| 2773 | /// \param OldParams If provided, template parameter list from a |
| 2774 | /// previous declaration of the same template. Default template |
| 2775 | /// arguments will be merged from the old template parameter list to |
| 2776 | /// the new template parameter list. |
| 2777 | /// |
| 2778 | /// \param TPC Describes the context in which we are checking the given |
| 2779 | /// template parameter list. |
| 2780 | /// |
| 2781 | /// \param SkipBody If we might have already made a prior merged definition |
| 2782 | /// of this template visible, the corresponding body-skipping information. |
| 2783 | /// Default argument redefinition is not an error when skipping such a body, |
| 2784 | /// because (under the ODR) we can assume the default arguments are the same |
| 2785 | /// as the prior merged definition. |
| 2786 | /// |
| 2787 | /// \returns true if an error occurred, false otherwise. |
| 2788 | bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, |
| 2789 | TemplateParameterList *OldParams, |
| 2790 | TemplateParamListContext TPC, |
| 2791 | SkipBodyInfo *SkipBody) { |
| 2792 | bool Invalid = false; |
| 2793 | |
| 2794 | // C++ [temp.param]p10: |
| 2795 | // The set of default template-arguments available for use with a |
| 2796 | // template declaration or definition is obtained by merging the |
| 2797 | // default arguments from the definition (if in scope) and all |
| 2798 | // declarations in scope in the same way default function |
| 2799 | // arguments are (8.3.6). |
| 2800 | bool SawDefaultArgument = false; |
| 2801 | SourceLocation PreviousDefaultArgLoc; |
| 2802 | |
| 2803 | // Dummy initialization to avoid warnings. |
| 2804 | TemplateParameterList::iterator OldParam = NewParams->end(); |
| 2805 | if (OldParams) |
| 2806 | OldParam = OldParams->begin(); |
| 2807 | |
| 2808 | bool RemoveDefaultArguments = false; |
| 2809 | for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
| 2810 | NewParamEnd = NewParams->end(); |
| 2811 | NewParam != NewParamEnd; ++NewParam) { |
| 2812 | // Whether we've seen a duplicate default argument in the same translation |
| 2813 | // unit. |
| 2814 | bool RedundantDefaultArg = false; |
| 2815 | // Whether we've found inconsis inconsitent default arguments in different |
| 2816 | // translation unit. |
| 2817 | bool InconsistentDefaultArg = false; |
| 2818 | // The name of the module which contains the inconsistent default argument. |
| 2819 | std::string PrevModuleName; |
| 2820 | |
| 2821 | SourceLocation OldDefaultLoc; |
| 2822 | SourceLocation NewDefaultLoc; |
| 2823 | |
| 2824 | // Variable used to diagnose missing default arguments |
| 2825 | bool MissingDefaultArg = false; |
| 2826 | |
| 2827 | // Variable used to diagnose non-final parameter packs |
| 2828 | bool SawParameterPack = false; |
| 2829 | |
| 2830 | if (TemplateTypeParmDecl *NewTypeParm |
| 2831 | = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { |
| 2832 | // Check the presence of a default argument here. |
| 2833 | if (NewTypeParm->hasDefaultArgument() && |
| 2834 | DiagnoseDefaultTemplateArgument(*this, TPC, |
| 2835 | NewTypeParm->getLocation(), |
| 2836 | NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() |
| 2837 | .getSourceRange())) |
| 2838 | NewTypeParm->removeDefaultArgument(); |
| 2839 | |
| 2840 | // Merge default arguments for template type parameters. |
| 2841 | TemplateTypeParmDecl *OldTypeParm |
| 2842 | = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr; |
| 2843 | if (NewTypeParm->isParameterPack()) { |
| 2844 | assert(!NewTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2845, __extension__ __PRETTY_FUNCTION__ )) |
| 2845 | "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2845, __extension__ __PRETTY_FUNCTION__ )); |
| 2846 | SawParameterPack = true; |
| 2847 | } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) && |
| 2848 | NewTypeParm->hasDefaultArgument() && |
| 2849 | (!SkipBody || !SkipBody->ShouldSkip)) { |
| 2850 | OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); |
| 2851 | NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); |
| 2852 | SawDefaultArgument = true; |
| 2853 | |
| 2854 | if (!OldTypeParm->isInAnotherModuleUnit()) |
| 2855 | RedundantDefaultArg = true; |
| 2856 | else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm, |
| 2857 | NewTypeParm)) { |
| 2858 | InconsistentDefaultArg = true; |
| 2859 | PrevModuleName = |
| 2860 | OldTypeParm->getImportedOwningModule()->getFullModuleName(); |
| 2861 | } |
| 2862 | PreviousDefaultArgLoc = NewDefaultLoc; |
| 2863 | } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { |
| 2864 | // Merge the default argument from the old declaration to the |
| 2865 | // new declaration. |
| 2866 | NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm); |
| 2867 | PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); |
| 2868 | } else if (NewTypeParm->hasDefaultArgument()) { |
| 2869 | SawDefaultArgument = true; |
| 2870 | PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); |
| 2871 | } else if (SawDefaultArgument) |
| 2872 | MissingDefaultArg = true; |
| 2873 | } else if (NonTypeTemplateParmDecl *NewNonTypeParm |
| 2874 | = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { |
| 2875 | // Check for unexpanded parameter packs. |
| 2876 | if (!NewNonTypeParm->isParameterPack() && |
| 2877 | DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), |
| 2878 | NewNonTypeParm->getTypeSourceInfo(), |
| 2879 | UPPC_NonTypeTemplateParameterType)) { |
| 2880 | Invalid = true; |
| 2881 | continue; |
| 2882 | } |
| 2883 | |
| 2884 | // Check the presence of a default argument here. |
| 2885 | if (NewNonTypeParm->hasDefaultArgument() && |
| 2886 | DiagnoseDefaultTemplateArgument(*this, TPC, |
| 2887 | NewNonTypeParm->getLocation(), |
| 2888 | NewNonTypeParm->getDefaultArgument()->getSourceRange())) { |
| 2889 | NewNonTypeParm->removeDefaultArgument(); |
| 2890 | } |
| 2891 | |
| 2892 | // Merge default arguments for non-type template parameters |
| 2893 | NonTypeTemplateParmDecl *OldNonTypeParm |
| 2894 | = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr; |
| 2895 | if (NewNonTypeParm->isParameterPack()) { |
| 2896 | assert(!NewNonTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2897, __extension__ __PRETTY_FUNCTION__ )) |
| 2897 | "Parameter packs can't have a default argument!")(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2897, __extension__ __PRETTY_FUNCTION__ )); |
| 2898 | if (!NewNonTypeParm->isPackExpansion()) |
| 2899 | SawParameterPack = true; |
| 2900 | } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) && |
| 2901 | NewNonTypeParm->hasDefaultArgument() && |
| 2902 | (!SkipBody || !SkipBody->ShouldSkip)) { |
| 2903 | OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
| 2904 | NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
| 2905 | SawDefaultArgument = true; |
| 2906 | if (!OldNonTypeParm->isInAnotherModuleUnit()) |
| 2907 | RedundantDefaultArg = true; |
| 2908 | else if (!getASTContext().isSameDefaultTemplateArgument( |
| 2909 | OldNonTypeParm, NewNonTypeParm)) { |
| 2910 | InconsistentDefaultArg = true; |
| 2911 | PrevModuleName = |
| 2912 | OldNonTypeParm->getImportedOwningModule()->getFullModuleName(); |
| 2913 | } |
| 2914 | PreviousDefaultArgLoc = NewDefaultLoc; |
| 2915 | } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { |
| 2916 | // Merge the default argument from the old declaration to the |
| 2917 | // new declaration. |
| 2918 | NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm); |
| 2919 | PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
| 2920 | } else if (NewNonTypeParm->hasDefaultArgument()) { |
| 2921 | SawDefaultArgument = true; |
| 2922 | PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
| 2923 | } else if (SawDefaultArgument) |
| 2924 | MissingDefaultArg = true; |
| 2925 | } else { |
| 2926 | TemplateTemplateParmDecl *NewTemplateParm |
| 2927 | = cast<TemplateTemplateParmDecl>(*NewParam); |
| 2928 | |
| 2929 | // Check for unexpanded parameter packs, recursively. |
| 2930 | if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { |
| 2931 | Invalid = true; |
| 2932 | continue; |
| 2933 | } |
| 2934 | |
| 2935 | // Check the presence of a default argument here. |
| 2936 | if (NewTemplateParm->hasDefaultArgument() && |
| 2937 | DiagnoseDefaultTemplateArgument(*this, TPC, |
| 2938 | NewTemplateParm->getLocation(), |
| 2939 | NewTemplateParm->getDefaultArgument().getSourceRange())) |
| 2940 | NewTemplateParm->removeDefaultArgument(); |
| 2941 | |
| 2942 | // Merge default arguments for template template parameters |
| 2943 | TemplateTemplateParmDecl *OldTemplateParm |
| 2944 | = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr; |
| 2945 | if (NewTemplateParm->isParameterPack()) { |
| 2946 | assert(!NewTemplateParm->hasDefaultArgument() &&(static_cast <bool> (!NewTemplateParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2947, __extension__ __PRETTY_FUNCTION__ )) |
| 2947 | "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTemplateParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2947, __extension__ __PRETTY_FUNCTION__ )); |
| 2948 | if (!NewTemplateParm->isPackExpansion()) |
| 2949 | SawParameterPack = true; |
| 2950 | } else if (OldTemplateParm && |
| 2951 | hasVisibleDefaultArgument(OldTemplateParm) && |
| 2952 | NewTemplateParm->hasDefaultArgument() && |
| 2953 | (!SkipBody || !SkipBody->ShouldSkip)) { |
| 2954 | OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); |
| 2955 | NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); |
| 2956 | SawDefaultArgument = true; |
| 2957 | if (!OldTemplateParm->isInAnotherModuleUnit()) |
| 2958 | RedundantDefaultArg = true; |
| 2959 | else if (!getASTContext().isSameDefaultTemplateArgument( |
| 2960 | OldTemplateParm, NewTemplateParm)) { |
| 2961 | InconsistentDefaultArg = true; |
| 2962 | PrevModuleName = |
| 2963 | OldTemplateParm->getImportedOwningModule()->getFullModuleName(); |
| 2964 | } |
| 2965 | PreviousDefaultArgLoc = NewDefaultLoc; |
| 2966 | } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { |
| 2967 | // Merge the default argument from the old declaration to the |
| 2968 | // new declaration. |
| 2969 | NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm); |
| 2970 | PreviousDefaultArgLoc |
| 2971 | = OldTemplateParm->getDefaultArgument().getLocation(); |
| 2972 | } else if (NewTemplateParm->hasDefaultArgument()) { |
| 2973 | SawDefaultArgument = true; |
| 2974 | PreviousDefaultArgLoc |
| 2975 | = NewTemplateParm->getDefaultArgument().getLocation(); |
| 2976 | } else if (SawDefaultArgument) |
| 2977 | MissingDefaultArg = true; |
| 2978 | } |
| 2979 | |
| 2980 | // C++11 [temp.param]p11: |
| 2981 | // If a template parameter of a primary class template or alias template |
| 2982 | // is a template parameter pack, it shall be the last template parameter. |
| 2983 | if (SawParameterPack && (NewParam + 1) != NewParamEnd && |
| 2984 | (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || |
| 2985 | TPC == TPC_TypeAliasTemplate)) { |
| 2986 | Diag((*NewParam)->getLocation(), |
| 2987 | diag::err_template_param_pack_must_be_last_template_parameter); |
| 2988 | Invalid = true; |
| 2989 | } |
| 2990 | |
| 2991 | // [basic.def.odr]/13: |
| 2992 | // There can be more than one definition of a |
| 2993 | // ... |
| 2994 | // default template argument |
| 2995 | // ... |
| 2996 | // in a program provided that each definition appears in a different |
| 2997 | // translation unit and the definitions satisfy the [same-meaning |
| 2998 | // criteria of the ODR]. |
| 2999 | // |
| 3000 | // Simply, the design of modules allows the definition of template default |
| 3001 | // argument to be repeated across translation unit. Note that the ODR is |
| 3002 | // checked elsewhere. But it is still not allowed to repeat template default |
| 3003 | // argument in the same translation unit. |
| 3004 | if (RedundantDefaultArg) { |
| 3005 | Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); |
| 3006 | Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); |
| 3007 | Invalid = true; |
| 3008 | } else if (InconsistentDefaultArg) { |
| 3009 | // We could only diagnose about the case that the OldParam is imported. |
| 3010 | // The case NewParam is imported should be handled in ASTReader. |
| 3011 | Diag(NewDefaultLoc, |
| 3012 | diag::err_template_param_default_arg_inconsistent_redefinition); |
| 3013 | Diag(OldDefaultLoc, |
| 3014 | diag::note_template_param_prev_default_arg_in_other_module) |
| 3015 | << PrevModuleName; |
| 3016 | Invalid = true; |
| 3017 | } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { |
| 3018 | // C++ [temp.param]p11: |
| 3019 | // If a template-parameter of a class template has a default |
| 3020 | // template-argument, each subsequent template-parameter shall either |
| 3021 | // have a default template-argument supplied or be a template parameter |
| 3022 | // pack. |
| 3023 | Diag((*NewParam)->getLocation(), |
| 3024 | diag::err_template_param_default_arg_missing); |
| 3025 | Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); |
| 3026 | Invalid = true; |
| 3027 | RemoveDefaultArguments = true; |
| 3028 | } |
| 3029 | |
| 3030 | // If we have an old template parameter list that we're merging |
| 3031 | // in, move on to the next parameter. |
| 3032 | if (OldParams) |
| 3033 | ++OldParam; |
| 3034 | } |
| 3035 | |
| 3036 | // We were missing some default arguments at the end of the list, so remove |
| 3037 | // all of the default arguments. |
| 3038 | if (RemoveDefaultArguments) { |
| 3039 | for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
| 3040 | NewParamEnd = NewParams->end(); |
| 3041 | NewParam != NewParamEnd; ++NewParam) { |
| 3042 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) |
| 3043 | TTP->removeDefaultArgument(); |
| 3044 | else if (NonTypeTemplateParmDecl *NTTP |
| 3045 | = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) |
| 3046 | NTTP->removeDefaultArgument(); |
| 3047 | else |
| 3048 | cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); |
| 3049 | } |
| 3050 | } |
| 3051 | |
| 3052 | return Invalid; |
| 3053 | } |
| 3054 | |
| 3055 | namespace { |
| 3056 | |
| 3057 | /// A class which looks for a use of a certain level of template |
| 3058 | /// parameter. |
| 3059 | struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { |
| 3060 | typedef RecursiveASTVisitor<DependencyChecker> super; |
| 3061 | |
| 3062 | unsigned Depth; |
| 3063 | |
| 3064 | // Whether we're looking for a use of a template parameter that makes the |
| 3065 | // overall construct type-dependent / a dependent type. This is strictly |
| 3066 | // best-effort for now; we may fail to match at all for a dependent type |
| 3067 | // in some cases if this is set. |
| 3068 | bool IgnoreNonTypeDependent; |
| 3069 | |
| 3070 | bool Match; |
| 3071 | SourceLocation MatchLoc; |
| 3072 | |
| 3073 | DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent) |
| 3074 | : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent), |
| 3075 | Match(false) {} |
| 3076 | |
| 3077 | DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent) |
| 3078 | : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) { |
| 3079 | NamedDecl *ND = Params->getParam(0); |
| 3080 | if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { |
| 3081 | Depth = PD->getDepth(); |
| 3082 | } else if (NonTypeTemplateParmDecl *PD = |
| 3083 | dyn_cast<NonTypeTemplateParmDecl>(ND)) { |
| 3084 | Depth = PD->getDepth(); |
| 3085 | } else { |
| 3086 | Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); |
| 3087 | } |
| 3088 | } |
| 3089 | |
| 3090 | bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { |
| 3091 | if (ParmDepth >= Depth) { |
| 3092 | Match = true; |
| 3093 | MatchLoc = Loc; |
| 3094 | return true; |
| 3095 | } |
| 3096 | return false; |
| 3097 | } |
| 3098 | |
| 3099 | bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) { |
| 3100 | // Prune out non-type-dependent expressions if requested. This can |
| 3101 | // sometimes result in us failing to find a template parameter reference |
| 3102 | // (if a value-dependent expression creates a dependent type), but this |
| 3103 | // mode is best-effort only. |
| 3104 | if (auto *E = dyn_cast_or_null<Expr>(S)) |
| 3105 | if (IgnoreNonTypeDependent && !E->isTypeDependent()) |
| 3106 | return true; |
| 3107 | return super::TraverseStmt(S, Q); |
| 3108 | } |
| 3109 | |
| 3110 | bool TraverseTypeLoc(TypeLoc TL) { |
| 3111 | if (IgnoreNonTypeDependent && !TL.isNull() && |
| 3112 | !TL.getType()->isDependentType()) |
| 3113 | return true; |
| 3114 | return super::TraverseTypeLoc(TL); |
| 3115 | } |
| 3116 | |
| 3117 | bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { |
| 3118 | return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc()); |
| 3119 | } |
| 3120 | |
| 3121 | bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { |
| 3122 | // For a best-effort search, keep looking until we find a location. |
| 3123 | return IgnoreNonTypeDependent || !Matches(T->getDepth()); |
| 3124 | } |
| 3125 | |
| 3126 | bool TraverseTemplateName(TemplateName N) { |
| 3127 | if (TemplateTemplateParmDecl *PD = |
| 3128 | dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) |
| 3129 | if (Matches(PD->getDepth())) |
| 3130 | return false; |
| 3131 | return super::TraverseTemplateName(N); |
| 3132 | } |
| 3133 | |
| 3134 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
| 3135 | if (NonTypeTemplateParmDecl *PD = |
| 3136 | dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) |
| 3137 | if (Matches(PD->getDepth(), E->getExprLoc())) |
| 3138 | return false; |
| 3139 | return super::VisitDeclRefExpr(E); |
| 3140 | } |
| 3141 | |
| 3142 | bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { |
| 3143 | return TraverseType(T->getReplacementType()); |
| 3144 | } |
| 3145 | |
| 3146 | bool |
| 3147 | VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { |
| 3148 | return TraverseTemplateArgument(T->getArgumentPack()); |
| 3149 | } |
| 3150 | |
| 3151 | bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { |
| 3152 | return TraverseType(T->getInjectedSpecializationType()); |
| 3153 | } |
| 3154 | }; |
| 3155 | } // end anonymous namespace |
| 3156 | |
| 3157 | /// Determines whether a given type depends on the given parameter |
| 3158 | /// list. |
| 3159 | static bool |
| 3160 | DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { |
| 3161 | if (!Params->size()) |
| 3162 | return false; |
| 3163 | |
| 3164 | DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false); |
| 3165 | Checker.TraverseType(T); |
| 3166 | return Checker.Match; |
| 3167 | } |
| 3168 | |
| 3169 | // Find the source range corresponding to the named type in the given |
| 3170 | // nested-name-specifier, if any. |
| 3171 | static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, |
| 3172 | QualType T, |
| 3173 | const CXXScopeSpec &SS) { |
| 3174 | NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); |
| 3175 | while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { |
| 3176 | if (const Type *CurType = NNS->getAsType()) { |
| 3177 | if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) |
| 3178 | return NNSLoc.getTypeLoc().getSourceRange(); |
| 3179 | } else |
| 3180 | break; |
| 3181 | |
| 3182 | NNSLoc = NNSLoc.getPrefix(); |
| 3183 | } |
| 3184 | |
| 3185 | return SourceRange(); |
| 3186 | } |
| 3187 | |
| 3188 | /// Match the given template parameter lists to the given scope |
| 3189 | /// specifier, returning the template parameter list that applies to the |
| 3190 | /// name. |
| 3191 | /// |
| 3192 | /// \param DeclStartLoc the start of the declaration that has a scope |
| 3193 | /// specifier or a template parameter list. |
| 3194 | /// |
| 3195 | /// \param DeclLoc The location of the declaration itself. |
| 3196 | /// |
| 3197 | /// \param SS the scope specifier that will be matched to the given template |
| 3198 | /// parameter lists. This scope specifier precedes a qualified name that is |
| 3199 | /// being declared. |
| 3200 | /// |
| 3201 | /// \param TemplateId The template-id following the scope specifier, if there |
| 3202 | /// is one. Used to check for a missing 'template<>'. |
| 3203 | /// |
| 3204 | /// \param ParamLists the template parameter lists, from the outermost to the |
| 3205 | /// innermost template parameter lists. |
| 3206 | /// |
| 3207 | /// \param IsFriend Whether to apply the slightly different rules for |
| 3208 | /// matching template parameters to scope specifiers in friend |
| 3209 | /// declarations. |
| 3210 | /// |
| 3211 | /// \param IsMemberSpecialization will be set true if the scope specifier |
| 3212 | /// denotes a fully-specialized type, and therefore this is a declaration of |
| 3213 | /// a member specialization. |
| 3214 | /// |
| 3215 | /// \returns the template parameter list, if any, that corresponds to the |
| 3216 | /// name that is preceded by the scope specifier @p SS. This template |
| 3217 | /// parameter list may have template parameters (if we're declaring a |
| 3218 | /// template) or may have no template parameters (if we're declaring a |
| 3219 | /// template specialization), or may be NULL (if what we're declaring isn't |
| 3220 | /// itself a template). |
| 3221 | TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( |
| 3222 | SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, |
| 3223 | TemplateIdAnnotation *TemplateId, |
| 3224 | ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, |
| 3225 | bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) { |
| 3226 | IsMemberSpecialization = false; |
| 3227 | Invalid = false; |
| 3228 | |
| 3229 | // The sequence of nested types to which we will match up the template |
| 3230 | // parameter lists. We first build this list by starting with the type named |
| 3231 | // by the nested-name-specifier and walking out until we run out of types. |
| 3232 | SmallVector<QualType, 4> NestedTypes; |
| 3233 | QualType T; |
| 3234 | if (SS.getScopeRep()) { |
| 3235 | if (CXXRecordDecl *Record |
| 3236 | = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) |
| 3237 | T = Context.getTypeDeclType(Record); |
| 3238 | else |
| 3239 | T = QualType(SS.getScopeRep()->getAsType(), 0); |
| 3240 | } |
| 3241 | |
| 3242 | // If we found an explicit specialization that prevents us from needing |
| 3243 | // 'template<>' headers, this will be set to the location of that |
| 3244 | // explicit specialization. |
| 3245 | SourceLocation ExplicitSpecLoc; |
| 3246 | |
| 3247 | while (!T.isNull()) { |
| 3248 | NestedTypes.push_back(T); |
| 3249 | |
| 3250 | // Retrieve the parent of a record type. |
| 3251 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
| 3252 | // If this type is an explicit specialization, we're done. |
| 3253 | if (ClassTemplateSpecializationDecl *Spec |
| 3254 | = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { |
| 3255 | if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && |
| 3256 | Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { |
| 3257 | ExplicitSpecLoc = Spec->getLocation(); |
| 3258 | break; |
| 3259 | } |
| 3260 | } else if (Record->getTemplateSpecializationKind() |
| 3261 | == TSK_ExplicitSpecialization) { |
| 3262 | ExplicitSpecLoc = Record->getLocation(); |
| 3263 | break; |
| 3264 | } |
| 3265 | |
| 3266 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) |
| 3267 | T = Context.getTypeDeclType(Parent); |
| 3268 | else |
| 3269 | T = QualType(); |
| 3270 | continue; |
| 3271 | } |
| 3272 | |
| 3273 | if (const TemplateSpecializationType *TST |
| 3274 | = T->getAs<TemplateSpecializationType>()) { |
| 3275 | if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
| 3276 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) |
| 3277 | T = Context.getTypeDeclType(Parent); |
| 3278 | else |
| 3279 | T = QualType(); |
| 3280 | continue; |
| 3281 | } |
| 3282 | } |
| 3283 | |
| 3284 | // Look one step prior in a dependent template specialization type. |
| 3285 | if (const DependentTemplateSpecializationType *DependentTST |
| 3286 | = T->getAs<DependentTemplateSpecializationType>()) { |
| 3287 | if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) |
| 3288 | T = QualType(NNS->getAsType(), 0); |
| 3289 | else |
| 3290 | T = QualType(); |
| 3291 | continue; |
| 3292 | } |
| 3293 | |
| 3294 | // Look one step prior in a dependent name type. |
| 3295 | if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ |
| 3296 | if (NestedNameSpecifier *NNS = DependentName->getQualifier()) |
| 3297 | T = QualType(NNS->getAsType(), 0); |
| 3298 | else |
| 3299 | T = QualType(); |
| 3300 | continue; |
| 3301 | } |
| 3302 | |
| 3303 | // Retrieve the parent of an enumeration type. |
| 3304 | if (const EnumType *EnumT = T->getAs<EnumType>()) { |
| 3305 | // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization |
| 3306 | // check here. |
| 3307 | EnumDecl *Enum = EnumT->getDecl(); |
| 3308 | |
| 3309 | // Get to the parent type. |
| 3310 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) |
| 3311 | T = Context.getTypeDeclType(Parent); |
| 3312 | else |
| 3313 | T = QualType(); |
| 3314 | continue; |
| 3315 | } |
| 3316 | |
| 3317 | T = QualType(); |
| 3318 | } |
| 3319 | // Reverse the nested types list, since we want to traverse from the outermost |
| 3320 | // to the innermost while checking template-parameter-lists. |
| 3321 | std::reverse(NestedTypes.begin(), NestedTypes.end()); |
| 3322 | |
| 3323 | // C++0x [temp.expl.spec]p17: |
| 3324 | // A member or a member template may be nested within many |
| 3325 | // enclosing class templates. In an explicit specialization for |
| 3326 | // such a member, the member declaration shall be preceded by a |
| 3327 | // template<> for each enclosing class template that is |
| 3328 | // explicitly specialized. |
| 3329 | bool SawNonEmptyTemplateParameterList = false; |
| 3330 | |
| 3331 | auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { |
| 3332 | if (SawNonEmptyTemplateParameterList) { |
| 3333 | if (!SuppressDiagnostic) |
| 3334 | Diag(DeclLoc, diag::err_specialize_member_of_template) |
| 3335 | << !Recovery << Range; |
| 3336 | Invalid = true; |
| 3337 | IsMemberSpecialization = false; |
| 3338 | return true; |
| 3339 | } |
| 3340 | |
| 3341 | return false; |
| 3342 | }; |
| 3343 | |
| 3344 | auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { |
| 3345 | // Check that we can have an explicit specialization here. |
| 3346 | if (CheckExplicitSpecialization(Range, true)) |
| 3347 | return true; |
| 3348 | |
| 3349 | // We don't have a template header, but we should. |
| 3350 | SourceLocation ExpectedTemplateLoc; |
| 3351 | if (!ParamLists.empty()) |
| 3352 | ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); |
| 3353 | else |
| 3354 | ExpectedTemplateLoc = DeclStartLoc; |
| 3355 | |
| 3356 | if (!SuppressDiagnostic) |
| 3357 | Diag(DeclLoc, diag::err_template_spec_needs_header) |
| 3358 | << Range |
| 3359 | << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); |
| 3360 | return false; |
| 3361 | }; |
| 3362 | |
| 3363 | unsigned ParamIdx = 0; |
| 3364 | for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; |
| 3365 | ++TypeIdx) { |
| 3366 | T = NestedTypes[TypeIdx]; |
| 3367 | |
| 3368 | // Whether we expect a 'template<>' header. |
| 3369 | bool NeedEmptyTemplateHeader = false; |
| 3370 | |
| 3371 | // Whether we expect a template header with parameters. |
| 3372 | bool NeedNonemptyTemplateHeader = false; |
| 3373 | |
| 3374 | // For a dependent type, the set of template parameters that we |
| 3375 | // expect to see. |
| 3376 | TemplateParameterList *ExpectedTemplateParams = nullptr; |
| 3377 | |
| 3378 | // C++0x [temp.expl.spec]p15: |
| 3379 | // A member or a member template may be nested within many enclosing |
| 3380 | // class templates. In an explicit specialization for such a member, the |
| 3381 | // member declaration shall be preceded by a template<> for each |
| 3382 | // enclosing class template that is explicitly specialized. |
| 3383 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
| 3384 | if (ClassTemplatePartialSpecializationDecl *Partial |
| 3385 | = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { |
| 3386 | ExpectedTemplateParams = Partial->getTemplateParameters(); |
| 3387 | NeedNonemptyTemplateHeader = true; |
| 3388 | } else if (Record->isDependentType()) { |
| 3389 | if (Record->getDescribedClassTemplate()) { |
| 3390 | ExpectedTemplateParams = Record->getDescribedClassTemplate() |
| 3391 | ->getTemplateParameters(); |
| 3392 | NeedNonemptyTemplateHeader = true; |
| 3393 | } |
| 3394 | } else if (ClassTemplateSpecializationDecl *Spec |
| 3395 | = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { |
| 3396 | // C++0x [temp.expl.spec]p4: |
| 3397 | // Members of an explicitly specialized class template are defined |
| 3398 | // in the same manner as members of normal classes, and not using |
| 3399 | // the template<> syntax. |
| 3400 | if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) |
| 3401 | NeedEmptyTemplateHeader = true; |
| 3402 | else |
| 3403 | continue; |
| 3404 | } else if (Record->getTemplateSpecializationKind()) { |
| 3405 | if (Record->getTemplateSpecializationKind() |
| 3406 | != TSK_ExplicitSpecialization && |
| 3407 | TypeIdx == NumTypes - 1) |
| 3408 | IsMemberSpecialization = true; |
| 3409 | |
| 3410 | continue; |
| 3411 | } |
| 3412 | } else if (const TemplateSpecializationType *TST |
| 3413 | = T->getAs<TemplateSpecializationType>()) { |
| 3414 | if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
| 3415 | ExpectedTemplateParams = Template->getTemplateParameters(); |
| 3416 | NeedNonemptyTemplateHeader = true; |
| 3417 | } |
| 3418 | } else if (T->getAs<DependentTemplateSpecializationType>()) { |
| 3419 | // FIXME: We actually could/should check the template arguments here |
| 3420 | // against the corresponding template parameter list. |
| 3421 | NeedNonemptyTemplateHeader = false; |
| 3422 | } |
| 3423 | |
| 3424 | // C++ [temp.expl.spec]p16: |
| 3425 | // In an explicit specialization declaration for a member of a class |
| 3426 | // template or a member template that ap- pears in namespace scope, the |
| 3427 | // member template and some of its enclosing class templates may remain |
| 3428 | // unspecialized, except that the declaration shall not explicitly |
| 3429 | // specialize a class member template if its en- closing class templates |
| 3430 | // are not explicitly specialized as well. |
| 3431 | if (ParamIdx < ParamLists.size()) { |
| 3432 | if (ParamLists[ParamIdx]->size() == 0) { |
| 3433 | if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
| 3434 | false)) |
| 3435 | return nullptr; |
| 3436 | } else |
| 3437 | SawNonEmptyTemplateParameterList = true; |
| 3438 | } |
| 3439 | |
| 3440 | if (NeedEmptyTemplateHeader) { |
| 3441 | // If we're on the last of the types, and we need a 'template<>' header |
| 3442 | // here, then it's a member specialization. |
| 3443 | if (TypeIdx == NumTypes - 1) |
| 3444 | IsMemberSpecialization = true; |
| 3445 | |
| 3446 | if (ParamIdx < ParamLists.size()) { |
| 3447 | if (ParamLists[ParamIdx]->size() > 0) { |
| 3448 | // The header has template parameters when it shouldn't. Complain. |
| 3449 | if (!SuppressDiagnostic) |
| 3450 | Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
| 3451 | diag::err_template_param_list_matches_nontemplate) |
| 3452 | << T |
| 3453 | << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), |
| 3454 | ParamLists[ParamIdx]->getRAngleLoc()) |
| 3455 | << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
| 3456 | Invalid = true; |
| 3457 | return nullptr; |
| 3458 | } |
| 3459 | |
| 3460 | // Consume this template header. |
| 3461 | ++ParamIdx; |
| 3462 | continue; |
| 3463 | } |
| 3464 | |
| 3465 | if (!IsFriend) |
| 3466 | if (DiagnoseMissingExplicitSpecialization( |
| 3467 | getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) |
| 3468 | return nullptr; |
| 3469 | |
| 3470 | continue; |
| 3471 | } |
| 3472 | |
| 3473 | if (NeedNonemptyTemplateHeader) { |
| 3474 | // In friend declarations we can have template-ids which don't |
| 3475 | // depend on the corresponding template parameter lists. But |
| 3476 | // assume that empty parameter lists are supposed to match this |
| 3477 | // template-id. |
| 3478 | if (IsFriend && T->isDependentType()) { |
| 3479 | if (ParamIdx < ParamLists.size() && |
| 3480 | DependsOnTemplateParameters(T, ParamLists[ParamIdx])) |
| 3481 | ExpectedTemplateParams = nullptr; |
| 3482 | else |
| 3483 | continue; |
| 3484 | } |
| 3485 | |
| 3486 | if (ParamIdx < ParamLists.size()) { |
| 3487 | // Check the template parameter list, if we can. |
| 3488 | if (ExpectedTemplateParams && |
| 3489 | !TemplateParameterListsAreEqual(ParamLists[ParamIdx], |
| 3490 | ExpectedTemplateParams, |
| 3491 | !SuppressDiagnostic, TPL_TemplateMatch)) |
| 3492 | Invalid = true; |
| 3493 | |
| 3494 | if (!Invalid && |
| 3495 | CheckTemplateParameterList(ParamLists[ParamIdx], nullptr, |
| 3496 | TPC_ClassTemplateMember)) |
| 3497 | Invalid = true; |
| 3498 | |
| 3499 | ++ParamIdx; |
| 3500 | continue; |
| 3501 | } |
| 3502 | |
| 3503 | if (!SuppressDiagnostic) |
| 3504 | Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) |
| 3505 | << T |
| 3506 | << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
| 3507 | Invalid = true; |
| 3508 | continue; |
| 3509 | } |
| 3510 | } |
| 3511 | |
| 3512 | // If there were at least as many template-ids as there were template |
| 3513 | // parameter lists, then there are no template parameter lists remaining for |
| 3514 | // the declaration itself. |
| 3515 | if (ParamIdx >= ParamLists.size()) { |
| 3516 | if (TemplateId && !IsFriend) { |
| 3517 | // We don't have a template header for the declaration itself, but we |
| 3518 | // should. |
| 3519 | DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, |
| 3520 | TemplateId->RAngleLoc)); |
| 3521 | |
| 3522 | // Fabricate an empty template parameter list for the invented header. |
| 3523 | return TemplateParameterList::Create(Context, SourceLocation(), |
| 3524 | SourceLocation(), std::nullopt, |
| 3525 | SourceLocation(), nullptr); |
| 3526 | } |
| 3527 | |
| 3528 | return nullptr; |
| 3529 | } |
| 3530 | |
| 3531 | // If there were too many template parameter lists, complain about that now. |
| 3532 | if (ParamIdx < ParamLists.size() - 1) { |
| 3533 | bool HasAnyExplicitSpecHeader = false; |
| 3534 | bool AllExplicitSpecHeaders = true; |
| 3535 | for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { |
| 3536 | if (ParamLists[I]->size() == 0) |
| 3537 | HasAnyExplicitSpecHeader = true; |
| 3538 | else |
| 3539 | AllExplicitSpecHeaders = false; |
| 3540 | } |
| 3541 | |
| 3542 | if (!SuppressDiagnostic) |
| 3543 | Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
| 3544 | AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers |
| 3545 | : diag::err_template_spec_extra_headers) |
| 3546 | << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), |
| 3547 | ParamLists[ParamLists.size() - 2]->getRAngleLoc()); |
| 3548 | |
| 3549 | // If there was a specialization somewhere, such that 'template<>' is |
| 3550 | // not required, and there were any 'template<>' headers, note where the |
| 3551 | // specialization occurred. |
| 3552 | if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader && |
| 3553 | !SuppressDiagnostic) |
| 3554 | Diag(ExplicitSpecLoc, |
| 3555 | diag::note_explicit_template_spec_does_not_need_header) |
| 3556 | << NestedTypes.back(); |
| 3557 | |
| 3558 | // We have a template parameter list with no corresponding scope, which |
| 3559 | // means that the resulting template declaration can't be instantiated |
| 3560 | // properly (we'll end up with dependent nodes when we shouldn't). |
| 3561 | if (!AllExplicitSpecHeaders) |
| 3562 | Invalid = true; |
| 3563 | } |
| 3564 | |
| 3565 | // C++ [temp.expl.spec]p16: |
| 3566 | // In an explicit specialization declaration for a member of a class |
| 3567 | // template or a member template that ap- pears in namespace scope, the |
| 3568 | // member template and some of its enclosing class templates may remain |
| 3569 | // unspecialized, except that the declaration shall not explicitly |
| 3570 | // specialize a class member template if its en- closing class templates |
| 3571 | // are not explicitly specialized as well. |
| 3572 | if (ParamLists.back()->size() == 0 && |
| 3573 | CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
| 3574 | false)) |
| 3575 | return nullptr; |
| 3576 | |
| 3577 | // Return the last template parameter list, which corresponds to the |
| 3578 | // entity being declared. |
| 3579 | return ParamLists.back(); |
| 3580 | } |
| 3581 | |
| 3582 | void Sema::NoteAllFoundTemplates(TemplateName Name) { |
| 3583 | if (TemplateDecl *Template = Name.getAsTemplateDecl()) { |
| 3584 | Diag(Template->getLocation(), diag::note_template_declared_here) |
| 3585 | << (isa<FunctionTemplateDecl>(Template) |
| 3586 | ? 0 |
| 3587 | : isa<ClassTemplateDecl>(Template) |
| 3588 | ? 1 |
| 3589 | : isa<VarTemplateDecl>(Template) |
| 3590 | ? 2 |
| 3591 | : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) |
| 3592 | << Template->getDeclName(); |
| 3593 | return; |
| 3594 | } |
| 3595 | |
| 3596 | if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { |
| 3597 | for (OverloadedTemplateStorage::iterator I = OST->begin(), |
| 3598 | IEnd = OST->end(); |
| 3599 | I != IEnd; ++I) |
| 3600 | Diag((*I)->getLocation(), diag::note_template_declared_here) |
| 3601 | << 0 << (*I)->getDeclName(); |
| 3602 | |
| 3603 | return; |
| 3604 | } |
| 3605 | } |
| 3606 | |
| 3607 | static QualType |
| 3608 | checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, |
| 3609 | ArrayRef<TemplateArgument> Converted, |
| 3610 | SourceLocation TemplateLoc, |
| 3611 | TemplateArgumentListInfo &TemplateArgs) { |
| 3612 | ASTContext &Context = SemaRef.getASTContext(); |
| 3613 | |
| 3614 | switch (BTD->getBuiltinTemplateKind()) { |
| 3615 | case BTK__make_integer_seq: { |
| 3616 | // Specializations of __make_integer_seq<S, T, N> are treated like |
| 3617 | // S<T, 0, ..., N-1>. |
| 3618 | |
| 3619 | QualType OrigType = Converted[1].getAsType(); |
| 3620 | // C++14 [inteseq.intseq]p1: |
| 3621 | // T shall be an integer type. |
| 3622 | if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) { |
| 3623 | SemaRef.Diag(TemplateArgs[1].getLocation(), |
| 3624 | diag::err_integer_sequence_integral_element_type); |
| 3625 | return QualType(); |
| 3626 | } |
| 3627 | |
| 3628 | TemplateArgument NumArgsArg = Converted[2]; |
| 3629 | if (NumArgsArg.isDependent()) |
| 3630 | return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), |
| 3631 | Converted); |
| 3632 | |
| 3633 | TemplateArgumentListInfo SyntheticTemplateArgs; |
| 3634 | // The type argument, wrapped in substitution sugar, gets reused as the |
| 3635 | // first template argument in the synthetic template argument list. |
| 3636 | SyntheticTemplateArgs.addArgument( |
| 3637 | TemplateArgumentLoc(TemplateArgument(OrigType), |
| 3638 | SemaRef.Context.getTrivialTypeSourceInfo( |
| 3639 | OrigType, TemplateArgs[1].getLocation()))); |
| 3640 | |
| 3641 | if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) { |
| 3642 | // Expand N into 0 ... N-1. |
| 3643 | for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); |
| 3644 | I < NumArgs; ++I) { |
| 3645 | TemplateArgument TA(Context, I, OrigType); |
| 3646 | SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc( |
| 3647 | TA, OrigType, TemplateArgs[2].getLocation())); |
| 3648 | } |
| 3649 | } else { |
| 3650 | // C++14 [inteseq.make]p1: |
| 3651 | // If N is negative the program is ill-formed. |
| 3652 | SemaRef.Diag(TemplateArgs[2].getLocation(), |
| 3653 | diag::err_integer_sequence_negative_length); |
| 3654 | return QualType(); |
| 3655 | } |
| 3656 | |
| 3657 | // The first template argument will be reused as the template decl that |
| 3658 | // our synthetic template arguments will be applied to. |
| 3659 | return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(), |
| 3660 | TemplateLoc, SyntheticTemplateArgs); |
| 3661 | } |
| 3662 | |
| 3663 | case BTK__type_pack_element: |
| 3664 | // Specializations of |
| 3665 | // __type_pack_element<Index, T_1, ..., T_N> |
| 3666 | // are treated like T_Index. |
| 3667 | assert(Converted.size() == 2 &&(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack" ) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\"" , "clang/lib/Sema/SemaTemplate.cpp", 3668, __extension__ __PRETTY_FUNCTION__ )) |
| 3668 | "__type_pack_element should be given an index and a parameter pack")(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack" ) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\"" , "clang/lib/Sema/SemaTemplate.cpp", 3668, __extension__ __PRETTY_FUNCTION__ )); |
| 3669 | |
| 3670 | TemplateArgument IndexArg = Converted[0], Ts = Converted[1]; |
| 3671 | if (IndexArg.isDependent() || Ts.isDependent()) |
| 3672 | return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), |
| 3673 | Converted); |
| 3674 | |
| 3675 | llvm::APSInt Index = IndexArg.getAsIntegral(); |
| 3676 | assert(Index >= 0 && "the index used with __type_pack_element should be of "(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of " "type std::size_t, and hence be non-negative") ? void (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\"" , "clang/lib/Sema/SemaTemplate.cpp", 3677, __extension__ __PRETTY_FUNCTION__ )) |
| 3677 | "type std::size_t, and hence be non-negative")(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of " "type std::size_t, and hence be non-negative") ? void (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\"" , "clang/lib/Sema/SemaTemplate.cpp", 3677, __extension__ __PRETTY_FUNCTION__ )); |
| 3678 | // If the Index is out of bounds, the program is ill-formed. |
| 3679 | if (Index >= Ts.pack_size()) { |
| 3680 | SemaRef.Diag(TemplateArgs[0].getLocation(), |
| 3681 | diag::err_type_pack_element_out_of_bounds); |
| 3682 | return QualType(); |
| 3683 | } |
| 3684 | |
| 3685 | // We simply return the type at index `Index`. |
| 3686 | int64_t N = Index.getExtValue(); |
| 3687 | return Ts.getPackAsArray()[N].getAsType(); |
| 3688 | } |
| 3689 | llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!" , "clang/lib/Sema/SemaTemplate.cpp", 3689); |
| 3690 | } |
| 3691 | |
| 3692 | /// Determine whether this alias template is "enable_if_t". |
| 3693 | /// libc++ >=14 uses "__enable_if_t" in C++11 mode. |
| 3694 | static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) { |
| 3695 | return AliasTemplate->getName().equals("enable_if_t") || |
| 3696 | AliasTemplate->getName().equals("__enable_if_t"); |
| 3697 | } |
| 3698 | |
| 3699 | /// Collect all of the separable terms in the given condition, which |
| 3700 | /// might be a conjunction. |
| 3701 | /// |
| 3702 | /// FIXME: The right answer is to convert the logical expression into |
| 3703 | /// disjunctive normal form, so we can find the first failed term |
| 3704 | /// within each possible clause. |
| 3705 | static void collectConjunctionTerms(Expr *Clause, |
| 3706 | SmallVectorImpl<Expr *> &Terms) { |
| 3707 | if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) { |
| 3708 | if (BinOp->getOpcode() == BO_LAnd) { |
| 3709 | collectConjunctionTerms(BinOp->getLHS(), Terms); |
| 3710 | collectConjunctionTerms(BinOp->getRHS(), Terms); |
| 3711 | return; |
| 3712 | } |
| 3713 | } |
| 3714 | |
| 3715 | Terms.push_back(Clause); |
| 3716 | } |
| 3717 | |
| 3718 | // The ranges-v3 library uses an odd pattern of a top-level "||" with |
| 3719 | // a left-hand side that is value-dependent but never true. Identify |
| 3720 | // the idiom and ignore that term. |
| 3721 | static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) { |
| 3722 | // Top-level '||'. |
| 3723 | auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts()); |
| 3724 | if (!BinOp) return Cond; |
| 3725 | |
| 3726 | if (BinOp->getOpcode() != BO_LOr) return Cond; |
| 3727 | |
| 3728 | // With an inner '==' that has a literal on the right-hand side. |
| 3729 | Expr *LHS = BinOp->getLHS(); |
| 3730 | auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts()); |
| 3731 | if (!InnerBinOp) return Cond; |
| 3732 | |
| 3733 | if (InnerBinOp->getOpcode() != BO_EQ || |
| 3734 | !isa<IntegerLiteral>(InnerBinOp->getRHS())) |
| 3735 | return Cond; |
| 3736 | |
| 3737 | // If the inner binary operation came from a macro expansion named |
| 3738 | // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side |
| 3739 | // of the '||', which is the real, user-provided condition. |
| 3740 | SourceLocation Loc = InnerBinOp->getExprLoc(); |
| 3741 | if (!Loc.isMacroID()) return Cond; |
| 3742 | |
| 3743 | StringRef MacroName = PP.getImmediateMacroName(Loc); |
| 3744 | if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_") |
| 3745 | return BinOp->getRHS(); |
| 3746 | |
| 3747 | return Cond; |
| 3748 | } |
| 3749 | |
| 3750 | namespace { |
| 3751 | |
| 3752 | // A PrinterHelper that prints more helpful diagnostics for some sub-expressions |
| 3753 | // within failing boolean expression, such as substituting template parameters |
| 3754 | // for actual types. |
| 3755 | class FailedBooleanConditionPrinterHelper : public PrinterHelper { |
| 3756 | public: |
| 3757 | explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P) |
| 3758 | : Policy(P) {} |
| 3759 | |
| 3760 | bool handledStmt(Stmt *E, raw_ostream &OS) override { |
| 3761 | const auto *DR = dyn_cast<DeclRefExpr>(E); |
| 3762 | if (DR && DR->getQualifier()) { |
| 3763 | // If this is a qualified name, expand the template arguments in nested |
| 3764 | // qualifiers. |
| 3765 | DR->getQualifier()->print(OS, Policy, true); |
| 3766 | // Then print the decl itself. |
| 3767 | const ValueDecl *VD = DR->getDecl(); |
| 3768 | OS << VD->getName(); |
| 3769 | if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) { |
| 3770 | // This is a template variable, print the expanded template arguments. |
| 3771 | printTemplateArgumentList( |
| 3772 | OS, IV->getTemplateArgs().asArray(), Policy, |
| 3773 | IV->getSpecializedTemplate()->getTemplateParameters()); |
| 3774 | } |
| 3775 | return true; |
| 3776 | } |
| 3777 | return false; |
| 3778 | } |
| 3779 | |
| 3780 | private: |
| 3781 | const PrintingPolicy Policy; |
| 3782 | }; |
| 3783 | |
| 3784 | } // end anonymous namespace |
| 3785 | |
| 3786 | std::pair<Expr *, std::string> |
| 3787 | Sema::findFailedBooleanCondition(Expr *Cond) { |
| 3788 | Cond = lookThroughRangesV3Condition(PP, Cond); |
| 3789 | |
| 3790 | // Separate out all of the terms in a conjunction. |
| 3791 | SmallVector<Expr *, 4> Terms; |
| 3792 | collectConjunctionTerms(Cond, Terms); |
| 3793 | |
| 3794 | // Determine which term failed. |
| 3795 | Expr *FailedCond = nullptr; |
| 3796 | for (Expr *Term : Terms) { |
| 3797 | Expr *TermAsWritten = Term->IgnoreParenImpCasts(); |
| 3798 | |
| 3799 | // Literals are uninteresting. |
| 3800 | if (isa<CXXBoolLiteralExpr>(TermAsWritten) || |
| 3801 | isa<IntegerLiteral>(TermAsWritten)) |
| 3802 | continue; |
| 3803 | |
| 3804 | // The initialization of the parameter from the argument is |
| 3805 | // a constant-evaluated context. |
| 3806 | EnterExpressionEvaluationContext ConstantEvaluated( |
| 3807 | *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
| 3808 | |
| 3809 | bool Succeeded; |
| 3810 | if (Term->EvaluateAsBooleanCondition(Succeeded, Context) && |
| 3811 | !Succeeded) { |
| 3812 | FailedCond = TermAsWritten; |
| 3813 | break; |
| 3814 | } |
| 3815 | } |
| 3816 | if (!FailedCond) |
| 3817 | FailedCond = Cond->IgnoreParenImpCasts(); |
| 3818 | |
| 3819 | std::string Description; |
| 3820 | { |
| 3821 | llvm::raw_string_ostream Out(Description); |
| 3822 | PrintingPolicy Policy = getPrintingPolicy(); |
| 3823 | Policy.PrintCanonicalTypes = true; |
| 3824 | FailedBooleanConditionPrinterHelper Helper(Policy); |
| 3825 | FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr); |
| 3826 | } |
| 3827 | return { FailedCond, Description }; |
| 3828 | } |
| 3829 | |
| 3830 | QualType Sema::CheckTemplateIdType(TemplateName Name, |
| 3831 | SourceLocation TemplateLoc, |
| 3832 | TemplateArgumentListInfo &TemplateArgs) { |
| 3833 | DependentTemplateName *DTN |
| 3834 | = Name.getUnderlying().getAsDependentTemplateName(); |
| 3835 | if (DTN && DTN->isIdentifier()) |
| 3836 | // When building a template-id where the template-name is dependent, |
| 3837 | // assume the template is a type template. Either our assumption is |
| 3838 | // correct, or the code is ill-formed and will be diagnosed when the |
| 3839 | // dependent name is substituted. |
| 3840 | return Context.getDependentTemplateSpecializationType( |
| 3841 | ETK_None, DTN->getQualifier(), DTN->getIdentifier(), |
| 3842 | TemplateArgs.arguments()); |
| 3843 | |
| 3844 | if (Name.getAsAssumedTemplateName() && |
| 3845 | resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc)) |
| 3846 | return QualType(); |
| 3847 | |
| 3848 | TemplateDecl *Template = Name.getAsTemplateDecl(); |
| 3849 | if (!Template || isa<FunctionTemplateDecl>(Template) || |
| 3850 | isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) { |
| 3851 | // We might have a substituted template template parameter pack. If so, |
| 3852 | // build a template specialization type for it. |
| 3853 | if (Name.getAsSubstTemplateTemplateParmPack()) |
| 3854 | return Context.getTemplateSpecializationType(Name, |
| 3855 | TemplateArgs.arguments()); |
| 3856 | |
| 3857 | Diag(TemplateLoc, diag::err_template_id_not_a_type) |
| 3858 | << Name; |
| 3859 | NoteAllFoundTemplates(Name); |
| 3860 | return QualType(); |
| 3861 | } |
| 3862 | |
| 3863 | // Check that the template argument list is well-formed for this |
| 3864 | // template. |
| 3865 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
| 3866 | if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false, |
| 3867 | SugaredConverted, CanonicalConverted, |
| 3868 | /*UpdateArgsWithConversions=*/true)) |
| 3869 | return QualType(); |
| 3870 | |
| 3871 | QualType CanonType; |
| 3872 | |
| 3873 | if (TypeAliasTemplateDecl *AliasTemplate = |
| 3874 | dyn_cast<TypeAliasTemplateDecl>(Template)) { |
| 3875 | |
| 3876 | // Find the canonical type for this type alias template specialization. |
| 3877 | TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); |
| 3878 | if (Pattern->isInvalidDecl()) |
| 3879 | return QualType(); |
| 3880 | |
| 3881 | // Only substitute for the innermost template argument list. |
| 3882 | MultiLevelTemplateArgumentList TemplateArgLists; |
| 3883 | TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted, |
| 3884 | /*Final=*/false); |
| 3885 | TemplateArgLists.addOuterRetainedLevels( |
| 3886 | AliasTemplate->getTemplateParameters()->getDepth()); |
| 3887 | |
| 3888 | LocalInstantiationScope Scope(*this); |
| 3889 | InstantiatingTemplate Inst(*this, TemplateLoc, Template); |
| 3890 | if (Inst.isInvalid()) |
| 3891 | return QualType(); |
| 3892 | |
| 3893 | CanonType = SubstType(Pattern->getUnderlyingType(), |
| 3894 | TemplateArgLists, AliasTemplate->getLocation(), |
| 3895 | AliasTemplate->getDeclName()); |
| 3896 | if (CanonType.isNull()) { |
| 3897 | // If this was enable_if and we failed to find the nested type |
| 3898 | // within enable_if in a SFINAE context, dig out the specific |
| 3899 | // enable_if condition that failed and present that instead. |
| 3900 | if (isEnableIfAliasTemplate(AliasTemplate)) { |
| 3901 | if (auto DeductionInfo = isSFINAEContext()) { |
| 3902 | if (*DeductionInfo && |
| 3903 | (*DeductionInfo)->hasSFINAEDiagnostic() && |
| 3904 | (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() == |
| 3905 | diag::err_typename_nested_not_found_enable_if && |
| 3906 | TemplateArgs[0].getArgument().getKind() |
| 3907 | == TemplateArgument::Expression) { |
| 3908 | Expr *FailedCond; |
| 3909 | std::string FailedDescription; |
| 3910 | std::tie(FailedCond, FailedDescription) = |
| 3911 | findFailedBooleanCondition(TemplateArgs[0].getSourceExpression()); |
| 3912 | |
| 3913 | // Remove the old SFINAE diagnostic. |
| 3914 | PartialDiagnosticAt OldDiag = |
| 3915 | {SourceLocation(), PartialDiagnostic::NullDiagnostic()}; |
| 3916 | (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag); |
| 3917 | |
| 3918 | // Add a new SFINAE diagnostic specifying which condition |
| 3919 | // failed. |
| 3920 | (*DeductionInfo)->addSFINAEDiagnostic( |
| 3921 | OldDiag.first, |
| 3922 | PDiag(diag::err_typename_nested_not_found_requirement) |
| 3923 | << FailedDescription |
| 3924 | << FailedCond->getSourceRange()); |
| 3925 | } |
| 3926 | } |
| 3927 | } |
| 3928 | |
| 3929 | return QualType(); |
| 3930 | } |
| 3931 | } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) { |
| 3932 | CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted, |
| 3933 | TemplateLoc, TemplateArgs); |
| 3934 | } else if (Name.isDependent() || |
| 3935 | TemplateSpecializationType::anyDependentTemplateArguments( |
| 3936 | TemplateArgs, CanonicalConverted)) { |
| 3937 | // This class template specialization is a dependent |
| 3938 | // type. Therefore, its canonical type is another class template |
| 3939 | // specialization type that contains all of the converted |
| 3940 | // arguments in canonical form. This ensures that, e.g., A<T> and |
| 3941 | // A<T, T> have identical types when A is declared as: |
| 3942 | // |
| 3943 | // template<typename T, typename U = T> struct A; |
| 3944 | CanonType = Context.getCanonicalTemplateSpecializationType( |
| 3945 | Name, CanonicalConverted); |
| 3946 | |
| 3947 | // This might work out to be a current instantiation, in which |
| 3948 | // case the canonical type needs to be the InjectedClassNameType. |
| 3949 | // |
| 3950 | // TODO: in theory this could be a simple hashtable lookup; most |
| 3951 | // changes to CurContext don't change the set of current |
| 3952 | // instantiations. |
| 3953 | if (isa<ClassTemplateDecl>(Template)) { |
| 3954 | for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { |
| 3955 | // If we get out to a namespace, we're done. |
| 3956 | if (Ctx->isFileContext()) break; |
| 3957 | |
| 3958 | // If this isn't a record, keep looking. |
| 3959 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); |
| 3960 | if (!Record) continue; |
| 3961 | |
| 3962 | // Look for one of the two cases with InjectedClassNameTypes |
| 3963 | // and check whether it's the same template. |
| 3964 | if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && |
| 3965 | !Record->getDescribedClassTemplate()) |
| 3966 | continue; |
| 3967 | |
| 3968 | // Fetch the injected class name type and check whether its |
| 3969 | // injected type is equal to the type we just built. |
| 3970 | QualType ICNT = Context.getTypeDeclType(Record); |
| 3971 | QualType Injected = cast<InjectedClassNameType>(ICNT) |
| 3972 | ->getInjectedSpecializationType(); |
| 3973 | |
| 3974 | if (CanonType != Injected->getCanonicalTypeInternal()) |
| 3975 | continue; |
| 3976 | |
| 3977 | // If so, the canonical type of this TST is the injected |
| 3978 | // class name type of the record we just found. |
| 3979 | assert(ICNT.isCanonical())(static_cast <bool> (ICNT.isCanonical()) ? void (0) : __assert_fail ("ICNT.isCanonical()", "clang/lib/Sema/SemaTemplate.cpp", 3979 , __extension__ __PRETTY_FUNCTION__)); |
| 3980 | CanonType = ICNT; |
| 3981 | break; |
| 3982 | } |
| 3983 | } |
| 3984 | } else if (ClassTemplateDecl *ClassTemplate = |
| 3985 | dyn_cast<ClassTemplateDecl>(Template)) { |
| 3986 | // Find the class template specialization declaration that |
| 3987 | // corresponds to these arguments. |
| 3988 | void *InsertPos = nullptr; |
| 3989 | ClassTemplateSpecializationDecl *Decl = |
| 3990 | ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); |
| 3991 | if (!Decl) { |
| 3992 | // This is the first time we have referenced this class template |
| 3993 | // specialization. Create the canonical declaration and add it to |
| 3994 | // the set of specializations. |
| 3995 | Decl = ClassTemplateSpecializationDecl::Create( |
| 3996 | Context, ClassTemplate->getTemplatedDecl()->getTagKind(), |
| 3997 | ClassTemplate->getDeclContext(), |
| 3998 | ClassTemplate->getTemplatedDecl()->getBeginLoc(), |
| 3999 | ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted, |
| 4000 | nullptr); |
| 4001 | ClassTemplate->AddSpecialization(Decl, InsertPos); |
| 4002 | if (ClassTemplate->isOutOfLine()) |
| 4003 | Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); |
| 4004 | } |
| 4005 | |
| 4006 | if (Decl->getSpecializationKind() == TSK_Undeclared && |
| 4007 | ClassTemplate->getTemplatedDecl()->hasAttrs()) { |
| 4008 | InstantiatingTemplate Inst(*this, TemplateLoc, Decl); |
| 4009 | if (!Inst.isInvalid()) { |
| 4010 | MultiLevelTemplateArgumentList TemplateArgLists(Template, |
| 4011 | CanonicalConverted, |
| 4012 | /*Final=*/false); |
| 4013 | InstantiateAttrsForDecl(TemplateArgLists, |
| 4014 | ClassTemplate->getTemplatedDecl(), Decl); |
| 4015 | } |
| 4016 | } |
| 4017 | |
| 4018 | // Diagnose uses of this specialization. |
| 4019 | (void)DiagnoseUseOfDecl(Decl, TemplateLoc); |
| 4020 | |
| 4021 | CanonType = Context.getTypeDeclType(Decl); |
| 4022 | assert(isa<RecordType>(CanonType) &&(static_cast <bool> (isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType") ? void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\"" , "clang/lib/Sema/SemaTemplate.cpp", 4023, __extension__ __PRETTY_FUNCTION__ )) |
| 4023 | "type of non-dependent specialization is not a RecordType")(static_cast <bool> (isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType") ? void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\"" , "clang/lib/Sema/SemaTemplate.cpp", 4023, __extension__ __PRETTY_FUNCTION__ )); |
| 4024 | } else { |
| 4025 | llvm_unreachable("Unhandled template kind")::llvm::llvm_unreachable_internal("Unhandled template kind", "clang/lib/Sema/SemaTemplate.cpp" , 4025); |
| 4026 | } |
| 4027 | |
| 4028 | // Build the fully-sugared type for this class template |
| 4029 | // specialization, which refers back to the class template |
| 4030 | // specialization we created or found. |
| 4031 | return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(), |
| 4032 | CanonType); |
| 4033 | } |
| 4034 | |
| 4035 | void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName, |
| 4036 | TemplateNameKind &TNK, |
| 4037 | SourceLocation NameLoc, |
| 4038 | IdentifierInfo *&II) { |
| 4039 | assert(TNK == TNK_Undeclared_template && "not an undeclared template name")(static_cast <bool> (TNK == TNK_Undeclared_template && "not an undeclared template name") ? void (0) : __assert_fail ("TNK == TNK_Undeclared_template && \"not an undeclared template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 4039, __extension__ __PRETTY_FUNCTION__ )); |
| 4040 | |
| 4041 | TemplateName Name = ParsedName.get(); |
| 4042 | auto *ATN = Name.getAsAssumedTemplateName(); |
| 4043 | assert(ATN && "not an assumed template name")(static_cast <bool> (ATN && "not an assumed template name" ) ? void (0) : __assert_fail ("ATN && \"not an assumed template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 4043, __extension__ __PRETTY_FUNCTION__ )); |
| 4044 | II = ATN->getDeclName().getAsIdentifierInfo(); |
| 4045 | |
| 4046 | if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) { |
| 4047 | // Resolved to a type template name. |
| 4048 | ParsedName = TemplateTy::make(Name); |
| 4049 | TNK = TNK_Type_template; |
| 4050 | } |
| 4051 | } |
| 4052 | |
| 4053 | bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, |
| 4054 | SourceLocation NameLoc, |
| 4055 | bool Diagnose) { |
| 4056 | // We assumed this undeclared identifier to be an (ADL-only) function |
| 4057 | // template name, but it was used in a context where a type was required. |
| 4058 | // Try to typo-correct it now. |
| 4059 | AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName(); |
| 4060 | assert(ATN && "not an assumed template name")(static_cast <bool> (ATN && "not an assumed template name" ) ? void (0) : __assert_fail ("ATN && \"not an assumed template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 4060, __extension__ __PRETTY_FUNCTION__ )); |
| 4061 | |
| 4062 | LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName); |
| 4063 | struct CandidateCallback : CorrectionCandidateCallback { |
| 4064 | bool ValidateCandidate(const TypoCorrection &TC) override { |
| 4065 | return TC.getCorrectionDecl() && |
| 4066 | getAsTypeTemplateDecl(TC.getCorrectionDecl()); |
| 4067 | } |
| 4068 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
| 4069 | return std::make_unique<CandidateCallback>(*this); |
| 4070 | } |
| 4071 | } FilterCCC; |
| 4072 | |
| 4073 | TypoCorrection Corrected = |
| 4074 | CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr, |
| 4075 | FilterCCC, CTK_ErrorRecovery); |
| 4076 | if (Corrected && Corrected.getFoundDecl()) { |
| 4077 | diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) |
| 4078 | << ATN->getDeclName()); |
| 4079 | Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()); |
| 4080 | return false; |
| 4081 | } |
| 4082 | |
| 4083 | if (Diagnose) |
| 4084 | Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName(); |
| 4085 | return true; |
| 4086 | } |
| 4087 | |
| 4088 | TypeResult Sema::ActOnTemplateIdType( |
| 4089 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
| 4090 | TemplateTy TemplateD, IdentifierInfo *TemplateII, |
| 4091 | SourceLocation TemplateIILoc, SourceLocation LAngleLoc, |
| 4092 | ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc, |
| 4093 | bool IsCtorOrDtorName, bool IsClassName, |
| 4094 | ImplicitTypenameContext AllowImplicitTypename) { |
| 4095 | if (SS.isInvalid()) |
| 4096 | return true; |
| 4097 | |
| 4098 | if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { |
| 4099 | DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false); |
| 4100 | |
| 4101 | // C++ [temp.res]p3: |
| 4102 | // A qualified-id that refers to a type and in which the |
| 4103 | // nested-name-specifier depends on a template-parameter (14.6.2) |
| 4104 | // shall be prefixed by the keyword typename to indicate that the |
| 4105 | // qualified-id denotes a type, forming an |
| 4106 | // elaborated-type-specifier (7.1.5.3). |
| 4107 | if (!LookupCtx && isDependentScopeSpecifier(SS)) { |
| 4108 | // C++2a relaxes some of those restrictions in [temp.res]p5. |
| 4109 | if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { |
| 4110 | if (getLangOpts().CPlusPlus20) |
| 4111 | Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename); |
| 4112 | else |
| 4113 | Diag(SS.getBeginLoc(), diag::ext_implicit_typename) |
| 4114 | << SS.getScopeRep() << TemplateII->getName() |
| 4115 | << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename "); |
| 4116 | } else |
| 4117 | Diag(SS.getBeginLoc(), diag::err_typename_missing_template) |
| 4118 | << SS.getScopeRep() << TemplateII->getName(); |
| 4119 | |
| 4120 | // FIXME: This is not quite correct recovery as we don't transform SS |
| 4121 | // into the corresponding dependent form (and we don't diagnose missing |
| 4122 | // 'template' keywords within SS as a result). |
| 4123 | return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc, |
| 4124 | TemplateD, TemplateII, TemplateIILoc, LAngleLoc, |
| 4125 | TemplateArgsIn, RAngleLoc); |
| 4126 | } |
| 4127 | |
| 4128 | // Per C++ [class.qual]p2, if the template-id was an injected-class-name, |
| 4129 | // it's not actually allowed to be used as a type in most cases. Because |
| 4130 | // we annotate it before we know whether it's valid, we have to check for |
| 4131 | // this case here. |
| 4132 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); |
| 4133 | if (LookupRD && LookupRD->getIdentifier() == TemplateII) { |
| 4134 | Diag(TemplateIILoc, |
| 4135 | TemplateKWLoc.isInvalid() |
| 4136 | ? diag::err_out_of_line_qualified_id_type_names_constructor |
| 4137 | : diag::ext_out_of_line_qualified_id_type_names_constructor) |
| 4138 | << TemplateII << 0 /*injected-class-name used as template name*/ |
| 4139 | << 1 /*if any keyword was present, it was 'template'*/; |
| 4140 | } |
| 4141 | } |
| 4142 | |
| 4143 | TemplateName Template = TemplateD.get(); |
| 4144 | if (Template.getAsAssumedTemplateName() && |
| 4145 | resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc)) |
| 4146 | return true; |
| 4147 | |
| 4148 | // Translate the parser's template argument list in our AST format. |
| 4149 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
| 4150 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
| 4151 | |
| 4152 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
| 4153 | assert(SS.getScopeRep() == DTN->getQualifier())(static_cast <bool> (SS.getScopeRep() == DTN->getQualifier ()) ? void (0) : __assert_fail ("SS.getScopeRep() == DTN->getQualifier()" , "clang/lib/Sema/SemaTemplate.cpp", 4153, __extension__ __PRETTY_FUNCTION__ )); |
| 4154 | QualType T = Context.getDependentTemplateSpecializationType( |
| 4155 | ETK_None, DTN->getQualifier(), DTN->getIdentifier(), |
| 4156 | TemplateArgs.arguments()); |
| 4157 | // Build type-source information. |
| 4158 | TypeLocBuilder TLB; |
| 4159 | DependentTemplateSpecializationTypeLoc SpecTL |
| 4160 | = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
| 4161 | SpecTL.setElaboratedKeywordLoc(SourceLocation()); |
| 4162 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 4163 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| 4164 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
| 4165 | SpecTL.setLAngleLoc(LAngleLoc); |
| 4166 | SpecTL.setRAngleLoc(RAngleLoc); |
| 4167 | for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
| 4168 | SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
| 4169 | return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); |
| 4170 | } |
| 4171 | |
| 4172 | QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); |
| 4173 | if (SpecTy.isNull()) |
| 4174 | return true; |
| 4175 | |
| 4176 | // Build type-source information. |
| 4177 | TypeLocBuilder TLB; |
| 4178 | TemplateSpecializationTypeLoc SpecTL = |
| 4179 | TLB.push<TemplateSpecializationTypeLoc>(SpecTy); |
| 4180 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| 4181 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
| 4182 | SpecTL.setLAngleLoc(LAngleLoc); |
| 4183 | SpecTL.setRAngleLoc(RAngleLoc); |
| 4184 | for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
| 4185 | SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); |
| 4186 | |
| 4187 | // Create an elaborated-type-specifier containing the nested-name-specifier. |
| 4188 | QualType ElTy = getElaboratedType( |
| 4189 | ETK_None, !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy); |
| 4190 | ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy); |
| 4191 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
| 4192 | if (!ElabTL.isEmpty()) |
| 4193 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 4194 | return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy)); |
| 4195 | } |
| 4196 | |
| 4197 | TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, |
| 4198 | TypeSpecifierType TagSpec, |
| 4199 | SourceLocation TagLoc, |
| 4200 | CXXScopeSpec &SS, |
| 4201 | SourceLocation TemplateKWLoc, |
| 4202 | TemplateTy TemplateD, |
| 4203 | SourceLocation TemplateLoc, |
| 4204 | SourceLocation LAngleLoc, |
| 4205 | ASTTemplateArgsPtr TemplateArgsIn, |
| 4206 | SourceLocation RAngleLoc) { |
| 4207 | if (SS.isInvalid()) |
| 4208 | return TypeResult(true); |
| 4209 | |
| 4210 | TemplateName Template = TemplateD.get(); |
| 4211 | |
| 4212 | // Translate the parser's template argument list in our AST format. |
| 4213 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
| 4214 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
| 4215 | |
| 4216 | // Determine the tag kind |
| 4217 | TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
| 4218 | ElaboratedTypeKeyword Keyword |
| 4219 | = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); |
| 4220 | |
| 4221 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
| 4222 | assert(SS.getScopeRep() == DTN->getQualifier())(static_cast <bool> (SS.getScopeRep() == DTN->getQualifier ()) ? void (0) : __assert_fail ("SS.getScopeRep() == DTN->getQualifier()" , "clang/lib/Sema/SemaTemplate.cpp", 4222, __extension__ __PRETTY_FUNCTION__ )); |
| 4223 | QualType T = Context.getDependentTemplateSpecializationType( |
| 4224 | Keyword, DTN->getQualifier(), DTN->getIdentifier(), |
| 4225 | TemplateArgs.arguments()); |
| 4226 | |
| 4227 | // Build type-source information. |
| 4228 | TypeLocBuilder TLB; |
| 4229 | DependentTemplateSpecializationTypeLoc SpecTL |
| 4230 | = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
| 4231 | SpecTL.setElaboratedKeywordLoc(TagLoc); |
| 4232 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 4233 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| 4234 | SpecTL.setTemplateNameLoc(TemplateLoc); |
| 4235 | SpecTL.setLAngleLoc(LAngleLoc); |
| 4236 | SpecTL.setRAngleLoc(RAngleLoc); |
| 4237 | for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
| 4238 | SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
| 4239 | return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); |
| 4240 | } |
| 4241 | |
| 4242 | if (TypeAliasTemplateDecl *TAT = |
| 4243 | dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { |
| 4244 | // C++0x [dcl.type.elab]p2: |
| 4245 | // If the identifier resolves to a typedef-name or the simple-template-id |
| 4246 | // resolves to an alias template specialization, the |
| 4247 | // elaborated-type-specifier is ill-formed. |
| 4248 | Diag(TemplateLoc, diag::err_tag_reference_non_tag) |
| 4249 | << TAT << NTK_TypeAliasTemplate << TagKind; |
| 4250 | Diag(TAT->getLocation(), diag::note_declared_at); |
| 4251 | } |
| 4252 | |
| 4253 | QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); |
| 4254 | if (Result.isNull()) |
| 4255 | return TypeResult(true); |
| 4256 | |
| 4257 | // Check the tag kind |
| 4258 | if (const RecordType *RT = Result->getAs<RecordType>()) { |
| 4259 | RecordDecl *D = RT->getDecl(); |
| 4260 | |
| 4261 | IdentifierInfo *Id = D->getIdentifier(); |
| 4262 | assert(Id && "templated class must have an identifier")(static_cast <bool> (Id && "templated class must have an identifier" ) ? void (0) : __assert_fail ("Id && \"templated class must have an identifier\"" , "clang/lib/Sema/SemaTemplate.cpp", 4262, __extension__ __PRETTY_FUNCTION__ )); |
| 4263 | |
| 4264 | if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, |
| 4265 | TagLoc, Id)) { |
| 4266 | Diag(TagLoc, diag::err_use_with_wrong_tag) |
| 4267 | << Result |
| 4268 | << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); |
| 4269 | Diag(D->getLocation(), diag::note_previous_use); |
| 4270 | } |
| 4271 | } |
| 4272 | |
| 4273 | // Provide source-location information for the template specialization. |
| 4274 | TypeLocBuilder TLB; |
| 4275 | TemplateSpecializationTypeLoc SpecTL |
| 4276 | = TLB.push<TemplateSpecializationTypeLoc>(Result); |
| 4277 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| 4278 | SpecTL.setTemplateNameLoc(TemplateLoc); |
| 4279 | SpecTL.setLAngleLoc(LAngleLoc); |
| 4280 | SpecTL.setRAngleLoc(RAngleLoc); |
| 4281 | for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
| 4282 | SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); |
| 4283 | |
| 4284 | // Construct an elaborated type containing the nested-name-specifier (if any) |
| 4285 | // and tag keyword. |
| 4286 | Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); |
| 4287 | ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); |
| 4288 | ElabTL.setElaboratedKeywordLoc(TagLoc); |
| 4289 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 4290 | return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); |
| 4291 | } |
| 4292 | |
| 4293 | static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, |
| 4294 | NamedDecl *PrevDecl, |
| 4295 | SourceLocation Loc, |
| 4296 | bool IsPartialSpecialization); |
| 4297 | |
| 4298 | static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); |
| 4299 | |
| 4300 | static bool isTemplateArgumentTemplateParameter( |
| 4301 | const TemplateArgument &Arg, unsigned Depth, unsigned Index) { |
| 4302 | switch (Arg.getKind()) { |
| 4303 | case TemplateArgument::Null: |
| 4304 | case TemplateArgument::NullPtr: |
| 4305 | case TemplateArgument::Integral: |
| 4306 | case TemplateArgument::Declaration: |
| 4307 | case TemplateArgument::Pack: |
| 4308 | case TemplateArgument::TemplateExpansion: |
| 4309 | return false; |
| 4310 | |
| 4311 | case TemplateArgument::Type: { |
| 4312 | QualType Type = Arg.getAsType(); |
| 4313 | const TemplateTypeParmType *TPT = |
| 4314 | Arg.getAsType()->getAs<TemplateTypeParmType>(); |
| 4315 | return TPT && !Type.hasQualifiers() && |
| 4316 | TPT->getDepth() == Depth && TPT->getIndex() == Index; |
| 4317 | } |
| 4318 | |
| 4319 | case TemplateArgument::Expression: { |
| 4320 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr()); |
| 4321 | if (!DRE || !DRE->getDecl()) |
| 4322 | return false; |
| 4323 | const NonTypeTemplateParmDecl *NTTP = |
| 4324 | dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); |
| 4325 | return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; |
| 4326 | } |
| 4327 | |
| 4328 | case TemplateArgument::Template: |
| 4329 | const TemplateTemplateParmDecl *TTP = |
| 4330 | dyn_cast_or_null<TemplateTemplateParmDecl>( |
| 4331 | Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); |
| 4332 | return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; |
| 4333 | } |
| 4334 | llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument" , "clang/lib/Sema/SemaTemplate.cpp", 4334); |
| 4335 | } |
| 4336 | |
| 4337 | static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, |
| 4338 | ArrayRef<TemplateArgument> Args) { |
| 4339 | if (Params->size() != Args.size()) |
| 4340 | return false; |
| 4341 | |
| 4342 | unsigned Depth = Params->getDepth(); |
| 4343 | |
| 4344 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { |
| 4345 | TemplateArgument Arg = Args[I]; |
| 4346 | |
| 4347 | // If the parameter is a pack expansion, the argument must be a pack |
| 4348 | // whose only element is a pack expansion. |
| 4349 | if (Params->getParam(I)->isParameterPack()) { |
| 4350 | if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || |
| 4351 | !Arg.pack_begin()->isPackExpansion()) |
| 4352 | return false; |
| 4353 | Arg = Arg.pack_begin()->getPackExpansionPattern(); |
| 4354 | } |
| 4355 | |
| 4356 | if (!isTemplateArgumentTemplateParameter(Arg, Depth, I)) |
| 4357 | return false; |
| 4358 | } |
| 4359 | |
| 4360 | return true; |
| 4361 | } |
| 4362 | |
| 4363 | template<typename PartialSpecDecl> |
| 4364 | static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) { |
| 4365 | if (Partial->getDeclContext()->isDependentContext()) |
| 4366 | return; |
| 4367 | |
| 4368 | // FIXME: Get the TDK from deduction in order to provide better diagnostics |
| 4369 | // for non-substitution-failure issues? |
| 4370 | TemplateDeductionInfo Info(Partial->getLocation()); |
| 4371 | if (S.isMoreSpecializedThanPrimary(Partial, Info)) |
| 4372 | return; |
| 4373 | |
| 4374 | auto *Template = Partial->getSpecializedTemplate(); |
| 4375 | S.Diag(Partial->getLocation(), |
| 4376 | diag::ext_partial_spec_not_more_specialized_than_primary) |
| 4377 | << isa<VarTemplateDecl>(Template); |
| 4378 | |
| 4379 | if (Info.hasSFINAEDiagnostic()) { |
| 4380 | PartialDiagnosticAt Diag = {SourceLocation(), |
| 4381 | PartialDiagnostic::NullDiagnostic()}; |
| 4382 | Info.takeSFINAEDiagnostic(Diag); |
| 4383 | SmallString<128> SFINAEArgString; |
| 4384 | Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString); |
| 4385 | S.Diag(Diag.first, |
| 4386 | diag::note_partial_spec_not_more_specialized_than_primary) |
| 4387 | << SFINAEArgString; |
| 4388 | } |
| 4389 | |
| 4390 | S.Diag(Template->getLocation(), diag::note_template_decl_here); |
| 4391 | SmallVector<const Expr *, 3> PartialAC, TemplateAC; |
| 4392 | Template->getAssociatedConstraints(TemplateAC); |
| 4393 | Partial->getAssociatedConstraints(PartialAC); |
| 4394 | S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template, |
| 4395 | TemplateAC); |
| 4396 | } |
| 4397 | |
| 4398 | static void |
| 4399 | noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, |
| 4400 | const llvm::SmallBitVector &DeducibleParams) { |
| 4401 | for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { |
| 4402 | if (!DeducibleParams[I]) { |
| 4403 | NamedDecl *Param = TemplateParams->getParam(I); |
| 4404 | if (Param->getDeclName()) |
| 4405 | S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) |
| 4406 | << Param->getDeclName(); |
| 4407 | else |
| 4408 | S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) |
| 4409 | << "(anonymous)"; |
| 4410 | } |
| 4411 | } |
| 4412 | } |
| 4413 | |
| 4414 | |
| 4415 | template<typename PartialSpecDecl> |
| 4416 | static void checkTemplatePartialSpecialization(Sema &S, |
| 4417 | PartialSpecDecl *Partial) { |
| 4418 | // C++1z [temp.class.spec]p8: (DR1495) |
| 4419 | // - The specialization shall be more specialized than the primary |
| 4420 | // template (14.5.5.2). |
| 4421 | checkMoreSpecializedThanPrimary(S, Partial); |
| 4422 | |
| 4423 | // C++ [temp.class.spec]p8: (DR1315) |
| 4424 | // - Each template-parameter shall appear at least once in the |
| 4425 | // template-id outside a non-deduced context. |
| 4426 | // C++1z [temp.class.spec.match]p3 (P0127R2) |
| 4427 | // If the template arguments of a partial specialization cannot be |
| 4428 | // deduced because of the structure of its template-parameter-list |
| 4429 | // and the template-id, the program is ill-formed. |
| 4430 | auto *TemplateParams = Partial->getTemplateParameters(); |
| 4431 | llvm::SmallBitVector DeducibleParams(TemplateParams->size()); |
| 4432 | S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, |
| 4433 | TemplateParams->getDepth(), DeducibleParams); |
| 4434 | |
| 4435 | if (!DeducibleParams.all()) { |
| 4436 | unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); |
| 4437 | S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible) |
| 4438 | << isa<VarTemplatePartialSpecializationDecl>(Partial) |
| 4439 | << (NumNonDeducible > 1) |
| 4440 | << SourceRange(Partial->getLocation(), |
| 4441 | Partial->getTemplateArgsAsWritten()->RAngleLoc); |
| 4442 | noteNonDeducibleParameters(S, TemplateParams, DeducibleParams); |
| 4443 | } |
| 4444 | } |
| 4445 | |
| 4446 | void Sema::CheckTemplatePartialSpecialization( |
| 4447 | ClassTemplatePartialSpecializationDecl *Partial) { |
| 4448 | checkTemplatePartialSpecialization(*this, Partial); |
| 4449 | } |
| 4450 | |
| 4451 | void Sema::CheckTemplatePartialSpecialization( |
| 4452 | VarTemplatePartialSpecializationDecl *Partial) { |
| 4453 | checkTemplatePartialSpecialization(*this, Partial); |
| 4454 | } |
| 4455 | |
| 4456 | void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) { |
| 4457 | // C++1z [temp.param]p11: |
| 4458 | // A template parameter of a deduction guide template that does not have a |
| 4459 | // default-argument shall be deducible from the parameter-type-list of the |
| 4460 | // deduction guide template. |
| 4461 | auto *TemplateParams = TD->getTemplateParameters(); |
| 4462 | llvm::SmallBitVector DeducibleParams(TemplateParams->size()); |
| 4463 | MarkDeducedTemplateParameters(TD, DeducibleParams); |
| 4464 | for (unsigned I = 0; I != TemplateParams->size(); ++I) { |
| 4465 | // A parameter pack is deducible (to an empty pack). |
| 4466 | auto *Param = TemplateParams->getParam(I); |
| 4467 | if (Param->isParameterPack() || hasVisibleDefaultArgument(Param)) |
| 4468 | DeducibleParams[I] = true; |
| 4469 | } |
| 4470 | |
| 4471 | if (!DeducibleParams.all()) { |
| 4472 | unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); |
| 4473 | Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible) |
| 4474 | << (NumNonDeducible > 1); |
| 4475 | noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams); |
| 4476 | } |
| 4477 | } |
| 4478 | |
| 4479 | DeclResult Sema::ActOnVarTemplateSpecialization( |
| 4480 | Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, |
| 4481 | TemplateParameterList *TemplateParams, StorageClass SC, |
| 4482 | bool IsPartialSpecialization) { |
| 4483 | // D must be variable template id. |
| 4484 | assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind ::IK_TemplateId && "Variable template specialization is declared with a template id." ) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template id.\"" , "clang/lib/Sema/SemaTemplate.cpp", 4485, __extension__ __PRETTY_FUNCTION__ )) |
| 4485 | "Variable template specialization is declared with a template id.")(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind ::IK_TemplateId && "Variable template specialization is declared with a template id." ) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template id.\"" , "clang/lib/Sema/SemaTemplate.cpp", 4485, __extension__ __PRETTY_FUNCTION__ )); |
| 4486 | |
| 4487 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; |
| 4488 | TemplateArgumentListInfo TemplateArgs = |
| 4489 | makeTemplateArgumentListInfo(*this, *TemplateId); |
| 4490 | SourceLocation TemplateNameLoc = D.getIdentifierLoc(); |
| 4491 | SourceLocation LAngleLoc = TemplateId->LAngleLoc; |
| 4492 | SourceLocation RAngleLoc = TemplateId->RAngleLoc; |
| 4493 | |
| 4494 | TemplateName Name = TemplateId->Template.get(); |
| 4495 | |
| 4496 | // The template-id must name a variable template. |
| 4497 | VarTemplateDecl *VarTemplate = |
| 4498 | dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl()); |
| 4499 | if (!VarTemplate) { |
| 4500 | NamedDecl *FnTemplate; |
| 4501 | if (auto *OTS = Name.getAsOverloadedTemplate()) |
| 4502 | FnTemplate = *OTS->begin(); |
| 4503 | else |
| 4504 | FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl()); |
| 4505 | if (FnTemplate) |
| 4506 | return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method) |
| 4507 | << FnTemplate->getDeclName(); |
| 4508 | return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) |
| 4509 | << IsPartialSpecialization; |
| 4510 | } |
| 4511 | |
| 4512 | // Check for unexpanded parameter packs in any of the template arguments. |
| 4513 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
| 4514 | if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], |
| 4515 | UPPC_PartialSpecialization)) |
| 4516 | return true; |
| 4517 | |
| 4518 | // Check that the template argument list is well-formed for this |
| 4519 | // template. |
| 4520 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
| 4521 | if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, |
| 4522 | false, SugaredConverted, CanonicalConverted, |
| 4523 | /*UpdateArgsWithConversions=*/true)) |
| 4524 | return true; |
| 4525 | |
| 4526 | // Find the variable template (partial) specialization declaration that |
| 4527 | // corresponds to these arguments. |
| 4528 | if (IsPartialSpecialization) { |
| 4529 | if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate, |
| 4530 | TemplateArgs.size(), |
| 4531 | CanonicalConverted)) |
| 4532 | return true; |
| 4533 | |
| 4534 | // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we |
| 4535 | // also do them during instantiation. |
| 4536 | if (!Name.isDependent() && |
| 4537 | !TemplateSpecializationType::anyDependentTemplateArguments( |
| 4538 | TemplateArgs, CanonicalConverted)) { |
| 4539 | Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) |
| 4540 | << VarTemplate->getDeclName(); |
| 4541 | IsPartialSpecialization = false; |
| 4542 | } |
| 4543 | |
| 4544 | if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), |
| 4545 | CanonicalConverted) && |
| 4546 | (!Context.getLangOpts().CPlusPlus20 || |
| 4547 | !TemplateParams->hasAssociatedConstraints())) { |
| 4548 | // C++ [temp.class.spec]p9b3: |
| 4549 | // |
| 4550 | // -- The argument list of the specialization shall not be identical |
| 4551 | // to the implicit argument list of the primary template. |
| 4552 | Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) |
| 4553 | << /*variable template*/ 1 |
| 4554 | << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) |
| 4555 | << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); |
| 4556 | // FIXME: Recover from this by treating the declaration as a redeclaration |
| 4557 | // of the primary template. |
| 4558 | return true; |
| 4559 | } |
| 4560 | } |
| 4561 | |
| 4562 | void *InsertPos = nullptr; |
| 4563 | VarTemplateSpecializationDecl *PrevDecl = nullptr; |
| 4564 | |
| 4565 | if (IsPartialSpecialization) |
| 4566 | PrevDecl = VarTemplate->findPartialSpecialization( |
| 4567 | CanonicalConverted, TemplateParams, InsertPos); |
| 4568 | else |
| 4569 | PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos); |
| 4570 | |
| 4571 | VarTemplateSpecializationDecl *Specialization = nullptr; |
| 4572 | |
| 4573 | // Check whether we can declare a variable template specialization in |
| 4574 | // the current scope. |
| 4575 | if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, |
| 4576 | TemplateNameLoc, |
| 4577 | IsPartialSpecialization)) |
| 4578 | return true; |
| 4579 | |
| 4580 | if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { |
| 4581 | // Since the only prior variable template specialization with these |
| 4582 | // arguments was referenced but not declared, reuse that |
| 4583 | // declaration node as our own, updating its source location and |
| 4584 | // the list of outer template parameters to reflect our new declaration. |
| 4585 | Specialization = PrevDecl; |
| 4586 | Specialization->setLocation(TemplateNameLoc); |
| 4587 | PrevDecl = nullptr; |
| 4588 | } else if (IsPartialSpecialization) { |
| 4589 | // Create a new class template partial specialization declaration node. |
| 4590 | VarTemplatePartialSpecializationDecl *PrevPartial = |
| 4591 | cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl); |
| 4592 | VarTemplatePartialSpecializationDecl *Partial = |
| 4593 | VarTemplatePartialSpecializationDecl::Create( |
| 4594 | Context, VarTemplate->getDeclContext(), TemplateKWLoc, |
| 4595 | TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC, |
| 4596 | CanonicalConverted, TemplateArgs); |
| 4597 | |
| 4598 | if (!PrevPartial) |
| 4599 | VarTemplate->AddPartialSpecialization(Partial, InsertPos); |
| 4600 | Specialization = Partial; |
| 4601 | |
| 4602 | // If we are providing an explicit specialization of a member variable |
| 4603 | // template specialization, make a note of that. |
| 4604 | if (PrevPartial && PrevPartial->getInstantiatedFromMember()) |
| 4605 | PrevPartial->setMemberSpecialization(); |
| 4606 | |
| 4607 | CheckTemplatePartialSpecialization(Partial); |
| 4608 | } else { |
| 4609 | // Create a new class template specialization declaration node for |
| 4610 | // this explicit specialization or friend declaration. |
| 4611 | Specialization = VarTemplateSpecializationDecl::Create( |
| 4612 | Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc, |
| 4613 | VarTemplate, DI->getType(), DI, SC, CanonicalConverted); |
| 4614 | Specialization->setTemplateArgsInfo(TemplateArgs); |
| 4615 | |
| 4616 | if (!PrevDecl) |
| 4617 | VarTemplate->AddSpecialization(Specialization, InsertPos); |
| 4618 | } |
| 4619 | |
| 4620 | // C++ [temp.expl.spec]p6: |
| 4621 | // If a template, a member template or the member of a class template is |
| 4622 | // explicitly specialized then that specialization shall be declared |
| 4623 | // before the first use of that specialization that would cause an implicit |
| 4624 | // instantiation to take place, in every translation unit in which such a |
| 4625 | // use occurs; no diagnostic is required. |
| 4626 | if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { |
| 4627 | bool Okay = false; |
| 4628 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
| 4629 | // Is there any previous explicit specialization declaration? |
| 4630 | if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { |
| 4631 | Okay = true; |
| 4632 | break; |
| 4633 | } |
| 4634 | } |
| 4635 | |
| 4636 | if (!Okay) { |
| 4637 | SourceRange Range(TemplateNameLoc, RAngleLoc); |
| 4638 | Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) |
| 4639 | << Name << Range; |
| 4640 | |
| 4641 | Diag(PrevDecl->getPointOfInstantiation(), |
| 4642 | diag::note_instantiation_required_here) |
| 4643 | << (PrevDecl->getTemplateSpecializationKind() != |
| 4644 | TSK_ImplicitInstantiation); |
| 4645 | return true; |
| 4646 | } |
| 4647 | } |
| 4648 | |
| 4649 | Specialization->setTemplateKeywordLoc(TemplateKWLoc); |
| 4650 | Specialization->setLexicalDeclContext(CurContext); |
| 4651 | |
| 4652 | // Add the specialization into its lexical context, so that it can |
| 4653 | // be seen when iterating through the list of declarations in that |
| 4654 | // context. However, specializations are not found by name lookup. |
| 4655 | CurContext->addDecl(Specialization); |
| 4656 | |
| 4657 | // Note that this is an explicit specialization. |
| 4658 | Specialization->setSpecializationKind(TSK_ExplicitSpecialization); |
| 4659 | |
| 4660 | if (PrevDecl) { |
| 4661 | // Check that this isn't a redefinition of this specialization, |
| 4662 | // merging with previous declarations. |
| 4663 | LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName, |
| 4664 | forRedeclarationInCurContext()); |
| 4665 | PrevSpec.addDecl(PrevDecl); |
| 4666 | D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec)); |
| 4667 | } else if (Specialization->isStaticDataMember() && |
| 4668 | Specialization->isOutOfLine()) { |
| 4669 | Specialization->setAccess(VarTemplate->getAccess()); |
| 4670 | } |
| 4671 | |
| 4672 | return Specialization; |
| 4673 | } |
| 4674 | |
| 4675 | namespace { |
| 4676 | /// A partial specialization whose template arguments have matched |
| 4677 | /// a given template-id. |
| 4678 | struct PartialSpecMatchResult { |
| 4679 | VarTemplatePartialSpecializationDecl *Partial; |
| 4680 | TemplateArgumentList *Args; |
| 4681 | }; |
| 4682 | } // end anonymous namespace |
| 4683 | |
| 4684 | DeclResult |
| 4685 | Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, |
| 4686 | SourceLocation TemplateNameLoc, |
| 4687 | const TemplateArgumentListInfo &TemplateArgs) { |
| 4688 | assert(Template && "A variable template id without template?")(static_cast <bool> (Template && "A variable template id without template?" ) ? void (0) : __assert_fail ("Template && \"A variable template id without template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 4688, __extension__ __PRETTY_FUNCTION__ )); |
| 4689 | |
| 4690 | // Check that the template argument list is well-formed for this template. |
| 4691 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
| 4692 | if (CheckTemplateArgumentList( |
| 4693 | Template, TemplateNameLoc, |
| 4694 | const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, |
| 4695 | SugaredConverted, CanonicalConverted, |
| 4696 | /*UpdateArgsWithConversions=*/true)) |
| 4697 | return true; |
| 4698 | |
| 4699 | // Produce a placeholder value if the specialization is dependent. |
| 4700 | if (Template->getDeclContext()->isDependentContext() || |
| 4701 | TemplateSpecializationType::anyDependentTemplateArguments( |
| 4702 | TemplateArgs, CanonicalConverted)) |
| 4703 | return DeclResult(); |
| 4704 | |
| 4705 | // Find the variable template specialization declaration that |
| 4706 | // corresponds to these arguments. |
| 4707 | void *InsertPos = nullptr; |
| 4708 | if (VarTemplateSpecializationDecl *Spec = |
| 4709 | Template->findSpecialization(CanonicalConverted, InsertPos)) { |
| 4710 | checkSpecializationReachability(TemplateNameLoc, Spec); |
| 4711 | // If we already have a variable template specialization, return it. |
| 4712 | return Spec; |
| 4713 | } |
| 4714 | |
| 4715 | // This is the first time we have referenced this variable template |
| 4716 | // specialization. Create the canonical declaration and add it to |
| 4717 | // the set of specializations, based on the closest partial specialization |
| 4718 | // that it represents. That is, |
| 4719 | VarDecl *InstantiationPattern = Template->getTemplatedDecl(); |
| 4720 | TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, |
| 4721 | CanonicalConverted); |
| 4722 | TemplateArgumentList *InstantiationArgs = &TemplateArgList; |
| 4723 | bool AmbiguousPartialSpec = false; |
| 4724 | typedef PartialSpecMatchResult MatchResult; |
| 4725 | SmallVector<MatchResult, 4> Matched; |
| 4726 | SourceLocation PointOfInstantiation = TemplateNameLoc; |
| 4727 | TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation, |
| 4728 | /*ForTakingAddress=*/false); |
| 4729 | |
| 4730 | // 1. Attempt to find the closest partial specialization that this |
| 4731 | // specializes, if any. |
| 4732 | // TODO: Unify with InstantiateClassTemplateSpecialization()? |
| 4733 | // Perhaps better after unification of DeduceTemplateArguments() and |
| 4734 | // getMoreSpecializedPartialSpecialization(). |
| 4735 | SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
| 4736 | Template->getPartialSpecializations(PartialSpecs); |
| 4737 | |
| 4738 | for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { |
| 4739 | VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; |
| 4740 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
| 4741 | |
| 4742 | if (TemplateDeductionResult Result = |
| 4743 | DeduceTemplateArguments(Partial, TemplateArgList, Info)) { |
| 4744 | // Store the failed-deduction information for use in diagnostics, later. |
| 4745 | // TODO: Actually use the failed-deduction info? |
| 4746 | FailedCandidates.addCandidate().set( |
| 4747 | DeclAccessPair::make(Template, AS_public), Partial, |
| 4748 | MakeDeductionFailureInfo(Context, Result, Info)); |
| 4749 | (void)Result; |
| 4750 | } else { |
| 4751 | Matched.push_back(PartialSpecMatchResult()); |
| 4752 | Matched.back().Partial = Partial; |
| 4753 | Matched.back().Args = Info.takeCanonical(); |
| 4754 | } |
| 4755 | } |
| 4756 | |
| 4757 | if (Matched.size() >= 1) { |
| 4758 | SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); |
| 4759 | if (Matched.size() == 1) { |
| 4760 | // -- If exactly one matching specialization is found, the |
| 4761 | // instantiation is generated from that specialization. |
| 4762 | // We don't need to do anything for this. |
| 4763 | } else { |
| 4764 | // -- If more than one matching specialization is found, the |
| 4765 | // partial order rules (14.5.4.2) are used to determine |
| 4766 | // whether one of the specializations is more specialized |
| 4767 | // than the others. If none of the specializations is more |
| 4768 | // specialized than all of the other matching |
| 4769 | // specializations, then the use of the variable template is |
| 4770 | // ambiguous and the program is ill-formed. |
| 4771 | for (SmallVector<MatchResult, 4>::iterator P = Best + 1, |
| 4772 | PEnd = Matched.end(); |
| 4773 | P != PEnd; ++P) { |
| 4774 | if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, |
| 4775 | PointOfInstantiation) == |
| 4776 | P->Partial) |
| 4777 | Best = P; |
| 4778 | } |
| 4779 | |
| 4780 | // Determine if the best partial specialization is more specialized than |
| 4781 | // the others. |
| 4782 | for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), |
| 4783 | PEnd = Matched.end(); |
| 4784 | P != PEnd; ++P) { |
| 4785 | if (P != Best && getMoreSpecializedPartialSpecialization( |
| 4786 | P->Partial, Best->Partial, |
| 4787 | PointOfInstantiation) != Best->Partial) { |
| 4788 | AmbiguousPartialSpec = true; |
| 4789 | break; |
| 4790 | } |
| 4791 | } |
| 4792 | } |
| 4793 | |
| 4794 | // Instantiate using the best variable template partial specialization. |
| 4795 | InstantiationPattern = Best->Partial; |
| 4796 | InstantiationArgs = Best->Args; |
| 4797 | } else { |
| 4798 | // -- If no match is found, the instantiation is generated |
| 4799 | // from the primary template. |
| 4800 | // InstantiationPattern = Template->getTemplatedDecl(); |
| 4801 | } |
| 4802 | |
| 4803 | // 2. Create the canonical declaration. |
| 4804 | // Note that we do not instantiate a definition until we see an odr-use |
| 4805 | // in DoMarkVarDeclReferenced(). |
| 4806 | // FIXME: LateAttrs et al.? |
| 4807 | VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( |
| 4808 | Template, InstantiationPattern, *InstantiationArgs, TemplateArgs, |
| 4809 | CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/); |
| 4810 | if (!Decl) |
| 4811 | return true; |
| 4812 | |
| 4813 | if (AmbiguousPartialSpec) { |
| 4814 | // Partial ordering did not produce a clear winner. Complain. |
| 4815 | Decl->setInvalidDecl(); |
| 4816 | Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) |
| 4817 | << Decl; |
| 4818 | |
| 4819 | // Print the matching partial specializations. |
| 4820 | for (MatchResult P : Matched) |
| 4821 | Diag(P.Partial->getLocation(), diag::note_partial_spec_match) |
| 4822 | << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(), |
| 4823 | *P.Args); |
| 4824 | return true; |
| 4825 | } |
| 4826 | |
| 4827 | if (VarTemplatePartialSpecializationDecl *D = |
| 4828 | dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern)) |
| 4829 | Decl->setInstantiationOf(D, InstantiationArgs); |
| 4830 | |
| 4831 | checkSpecializationReachability(TemplateNameLoc, Decl); |
| 4832 | |
| 4833 | assert(Decl && "No variable template specialization?")(static_cast <bool> (Decl && "No variable template specialization?" ) ? void (0) : __assert_fail ("Decl && \"No variable template specialization?\"" , "clang/lib/Sema/SemaTemplate.cpp", 4833, __extension__ __PRETTY_FUNCTION__ )); |
| 4834 | return Decl; |
| 4835 | } |
| 4836 | |
| 4837 | ExprResult |
| 4838 | Sema::CheckVarTemplateId(const CXXScopeSpec &SS, |
| 4839 | const DeclarationNameInfo &NameInfo, |
| 4840 | VarTemplateDecl *Template, SourceLocation TemplateLoc, |
| 4841 | const TemplateArgumentListInfo *TemplateArgs) { |
| 4842 | |
| 4843 | DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(), |
| 4844 | *TemplateArgs); |
| 4845 | if (Decl.isInvalid()) |
| 4846 | return ExprError(); |
| 4847 | |
| 4848 | if (!Decl.get()) |
| 4849 | return ExprResult(); |
| 4850 | |
| 4851 | VarDecl *Var = cast<VarDecl>(Decl.get()); |
| 4852 | if (!Var->getTemplateSpecializationKind()) |
| 4853 | Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, |
| 4854 | NameInfo.getLoc()); |
| 4855 | |
| 4856 | // Build an ordinary singleton decl ref. |
| 4857 | return BuildDeclarationNameExpr(SS, NameInfo, Var, |
| 4858 | /*FoundD=*/nullptr, TemplateArgs); |
| 4859 | } |
| 4860 | |
| 4861 | void Sema::diagnoseMissingTemplateArguments(TemplateName Name, |
| 4862 | SourceLocation Loc) { |
| 4863 | Diag(Loc, diag::err_template_missing_args) |
| 4864 | << (int)getTemplateNameKindForDiagnostics(Name) << Name; |
| 4865 | if (TemplateDecl *TD = Name.getAsTemplateDecl()) { |
| 4866 | Diag(TD->getLocation(), diag::note_template_decl_here) |
| 4867 | << TD->getTemplateParameters()->getSourceRange(); |
| 4868 | } |
| 4869 | } |
| 4870 | |
| 4871 | ExprResult |
| 4872 | Sema::CheckConceptTemplateId(const CXXScopeSpec &SS, |
| 4873 | SourceLocation TemplateKWLoc, |
| 4874 | const DeclarationNameInfo &ConceptNameInfo, |
| 4875 | NamedDecl *FoundDecl, |
| 4876 | ConceptDecl *NamedConcept, |
| 4877 | const TemplateArgumentListInfo *TemplateArgs) { |
| 4878 | assert(NamedConcept && "A concept template id without a template?")(static_cast <bool> (NamedConcept && "A concept template id without a template?" ) ? void (0) : __assert_fail ("NamedConcept && \"A concept template id without a template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 4878, __extension__ __PRETTY_FUNCTION__ )); |
| 4879 | |
| 4880 | llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
| 4881 | if (CheckTemplateArgumentList( |
| 4882 | NamedConcept, ConceptNameInfo.getLoc(), |
| 4883 | const_cast<TemplateArgumentListInfo &>(*TemplateArgs), |
| 4884 | /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted, |
| 4885 | /*UpdateArgsWithConversions=*/false)) |
| 4886 | return ExprError(); |
| 4887 | |
| 4888 | auto *CSD = ImplicitConceptSpecializationDecl::Create( |
| 4889 | Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(), |
| 4890 | CanonicalConverted); |
| 4891 | ConstraintSatisfaction Satisfaction; |
| 4892 | bool AreArgsDependent = |
| 4893 | TemplateSpecializationType::anyDependentTemplateArguments( |
| 4894 | *TemplateArgs, CanonicalConverted); |
| 4895 | MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted, |
| 4896 | /*Final=*/false); |
| 4897 | LocalInstantiationScope Scope(*this); |
| 4898 | |
| 4899 | EnterExpressionEvaluationContext EECtx{ |
| 4900 | *this, ExpressionEvaluationContext::ConstantEvaluated, CSD}; |
| 4901 | |
| 4902 | if (!AreArgsDependent && |
| 4903 | CheckConstraintSatisfaction( |
| 4904 | NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL, |
| 4905 | SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(), |
| 4906 | TemplateArgs->getRAngleLoc()), |
| 4907 | Satisfaction)) |
| 4908 | return ExprError(); |
| 4909 | |
| 4910 | return ConceptSpecializationExpr::Create( |
| 4911 | Context, |
| 4912 | SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{}, |
| 4913 | TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept, |
| 4914 | ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), CSD, |
| 4915 | AreArgsDependent ? nullptr : &Satisfaction); |
| 4916 | } |
| 4917 | |
| 4918 | ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, |
| 4919 | SourceLocation TemplateKWLoc, |
| 4920 | LookupResult &R, |
| 4921 | bool RequiresADL, |
| 4922 | const TemplateArgumentListInfo *TemplateArgs) { |
| 4923 | // FIXME: Can we do any checking at this point? I guess we could check the |
| 4924 | // template arguments that we have against the template name, if the template |
| 4925 | // name refers to a single template. That's not a terribly common case, |
| 4926 | // though. |
| 4927 | // foo<int> could identify a single function unambiguously |
| 4928 | // This approach does NOT work, since f<int>(1); |
| 4929 | // gets resolved prior to resorting to overload resolution |
| 4930 | // i.e., template<class T> void f(double); |
| 4931 | // vs template<class T, class U> void f(U); |
| 4932 | |
| 4933 | // These should be filtered out by our callers. |
| 4934 | assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")(static_cast <bool> (!R.isAmbiguous() && "ambiguous lookup when building templateid" ) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\"" , "clang/lib/Sema/SemaTemplate.cpp", 4934, __extension__ __PRETTY_FUNCTION__ )); |
| 4935 | |
| 4936 | // Non-function templates require a template argument list. |
| 4937 | if (auto *TD = R.getAsSingle<TemplateDecl>()) { |
| 4938 | if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) { |
| 4939 | diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc()); |
| 4940 | return ExprError(); |
| 4941 | } |
| 4942 | } |
| 4943 | |
| 4944 | // In C++1y, check variable template ids. |
| 4945 | if (R.getAsSingle<VarTemplateDecl>()) { |
| 4946 | ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(), |
| 4947 | R.getAsSingle<VarTemplateDecl>(), |
| 4948 | TemplateKWLoc, TemplateArgs); |
| 4949 | if (Res.isInvalid() || Res.isUsable()) |
| 4950 | return Res; |
| 4951 | // Result is dependent. Carry on to build an UnresolvedLookupEpxr. |
| 4952 | } |
| 4953 | |
| 4954 | if (R.getAsSingle<ConceptDecl>()) { |
| 4955 | return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(), |
| 4956 | R.getFoundDecl(), |
| 4957 | R.getAsSingle<ConceptDecl>(), TemplateArgs); |
| 4958 | } |
| 4959 | |
| 4960 | // We don't want lookup warnings at this point. |
| 4961 | R.suppressDiagnostics(); |
| 4962 | |
| 4963 | UnresolvedLookupExpr *ULE |
| 4964 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), |
| 4965 | SS.getWithLocInContext(Context), |
| 4966 | TemplateKWLoc, |
| 4967 | R.getLookupNameInfo(), |
| 4968 | RequiresADL, TemplateArgs, |
| 4969 | R.begin(), R.end()); |
| 4970 | |
| 4971 | return ULE; |
| 4972 | } |
| 4973 | |
| 4974 | // We actually only call this from template instantiation. |
| 4975 | ExprResult |
| 4976 | Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, |
| 4977 | SourceLocation TemplateKWLoc, |
| 4978 | const DeclarationNameInfo &NameInfo, |
| 4979 | const TemplateArgumentListInfo *TemplateArgs) { |
| 4980 | |
| 4981 | assert(TemplateArgs || TemplateKWLoc.isValid())(static_cast <bool> (TemplateArgs || TemplateKWLoc.isValid ()) ? void (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()" , "clang/lib/Sema/SemaTemplate.cpp", 4981, __extension__ __PRETTY_FUNCTION__ )); |
| 4982 | DeclContext *DC; |
| 4983 | if (!(DC = computeDeclContext(SS, false)) || |
| 4984 | DC->isDependentContext() || |
| 4985 | RequireCompleteDeclContext(SS, DC)) |
| 4986 | return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); |
| 4987 | |
| 4988 | bool MemberOfUnknownSpecialization; |
| 4989 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
| 4990 | if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(), |
| 4991 | /*Entering*/false, MemberOfUnknownSpecialization, |
| 4992 | TemplateKWLoc)) |
| 4993 | return ExprError(); |
| 4994 | |
| 4995 | if (R.isAmbiguous()) |
| 4996 | return ExprError(); |
| 4997 | |
| 4998 | if (R.empty()) { |
| 4999 | Diag(NameInfo.getLoc(), diag::err_no_member) |
| 5000 | << NameInfo.getName() << DC << SS.getRange(); |
| 5001 | return ExprError(); |
| 5002 | } |
| 5003 | |
| 5004 | if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { |
| 5005 | Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template) |
| 5006 | << SS.getScopeRep() |
| 5007 | << NameInfo.getName().getAsString() << SS.getRange(); |
| 5008 | Diag(Temp->getLocation(), diag::note_referenced_class_template); |
| 5009 | return ExprError(); |
| 5010 | } |
| 5011 | |
| 5012 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs); |
| 5013 | } |
| 5014 | |
| 5015 | /// Form a template name from a name that is syntactically required to name a |
| 5016 | /// template, either due to use of the 'template' keyword or because a name in |
| 5017 | /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4). |
| 5018 | /// |
| 5019 | /// This action forms a template name given the name of the template and its |
| 5020 | /// optional scope specifier. This is used when the 'template' keyword is used |
| 5021 | /// or when the parsing context unambiguously treats a following '<' as |
| 5022 | /// introducing a template argument list. Note that this may produce a |
| 5023 | /// non-dependent template name if we can perform the lookup now and identify |
| 5024 | /// the named template. |
| 5025 | /// |
| 5026 | /// For example, given "x.MetaFun::template apply", the scope specifier |
| 5027 | /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location |
| 5028 | /// of the "template" keyword, and "apply" is the \p Name. |
| 5029 | TemplateNameKind Sema::ActOnTemplateName(Scope *S, |
| 5030 | CXXScopeSpec &SS, |
| 5031 | SourceLocation TemplateKWLoc, |
| 5032 | const UnqualifiedId &Name, |
| 5033 | ParsedType ObjectType, |
| 5034 | bool EnteringContext, |
| 5035 | TemplateTy &Result, |
| 5036 | bool AllowInjectedClassName) { |
| 5037 | if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent()) |
| 5038 | Diag(TemplateKWLoc, |
| 5039 | getLangOpts().CPlusPlus11 ? |
| 5040 | diag::warn_cxx98_compat_template_outside_of_template : |
| 5041 | diag::ext_template_outside_of_template) |
| 5042 | << FixItHint::CreateRemoval(TemplateKWLoc); |
| 5043 | |
| 5044 | if (SS.isInvalid()) |
| 5045 | return TNK_Non_template; |
| 5046 | |
| 5047 | // Figure out where isTemplateName is going to look. |
| 5048 | DeclContext *LookupCtx = nullptr; |
| 5049 | if (SS.isNotEmpty()) |
| 5050 | LookupCtx = computeDeclContext(SS, EnteringContext); |
| 5051 | else if (ObjectType) |
| 5052 | LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType)); |
| 5053 | |
| 5054 | // C++0x [temp.names]p5: |
| 5055 | // If a name prefixed by the keyword template is not the name of |
| 5056 | // a template, the program is ill-formed. [Note: the keyword |
| 5057 | // template may not be applied to non-template members of class |
| 5058 | // templates. -end note ] [ Note: as is the case with the |
| 5059 | // typename prefix, the template prefix is allowed in cases |
| 5060 | // where it is not strictly necessary; i.e., when the |
| 5061 | // nested-name-specifier or the expression on the left of the -> |
| 5062 | // or . is not dependent on a template-parameter, or the use |
| 5063 | // does not appear in the scope of a template. -end note] |
| 5064 | // |
| 5065 | // Note: C++03 was more strict here, because it banned the use of |
| 5066 | // the "template" keyword prior to a template-name that was not a |
| 5067 | // dependent name. C++ DR468 relaxed this requirement (the |
| 5068 | // "template" keyword is now permitted). We follow the C++0x |
| 5069 | // rules, even in C++03 mode with a warning, retroactively applying the DR. |
| 5070 | bool MemberOfUnknownSpecialization; |
| 5071 | TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name, |
| 5072 | ObjectType, EnteringContext, Result, |
| 5073 | MemberOfUnknownSpecialization); |
| 5074 | if (TNK != TNK_Non_template) { |
| 5075 | // We resolved this to a (non-dependent) template name. Return it. |
| 5076 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); |
| 5077 | if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD && |
| 5078 | Name.getKind() == UnqualifiedIdKind::IK_Identifier && |
| 5079 | Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) { |
| 5080 | // C++14 [class.qual]p2: |
| 5081 | // In a lookup in which function names are not ignored and the |
| 5082 | // nested-name-specifier nominates a class C, if the name specified |
| 5083 | // [...] is the injected-class-name of C, [...] the name is instead |
| 5084 | // considered to name the constructor |
| 5085 | // |
| 5086 | // We don't get here if naming the constructor would be valid, so we |
| 5087 | // just reject immediately and recover by treating the |
| 5088 | // injected-class-name as naming the template. |
| 5089 | Diag(Name.getBeginLoc(), |
| 5090 | diag::ext_out_of_line_qualified_id_type_names_constructor) |
| 5091 | << Name.Identifier |
| 5092 | << 0 /*injected-class-name used as template name*/ |
| 5093 | << TemplateKWLoc.isValid(); |
| 5094 | } |
| 5095 | return TNK; |
| 5096 | } |
| 5097 | |
| 5098 | if (!MemberOfUnknownSpecialization) { |
| 5099 | // Didn't find a template name, and the lookup wasn't dependent. |
| 5100 | // Do the lookup again to determine if this is a "nothing found" case or |
| 5101 | // a "not a template" case. FIXME: Refactor isTemplateName so we don't |
| 5102 | // need to do this. |
| 5103 | DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name); |
| 5104 | LookupResult R(*this, DNI.getName(), Name.getBeginLoc(), |
| 5105 | LookupOrdinaryName); |
| 5106 | bool MOUS; |
| 5107 | // Tell LookupTemplateName that we require a template so that it diagnoses |
| 5108 | // cases where it finds a non-template. |
| 5109 | RequiredTemplateKind RTK = TemplateKWLoc.isValid() |
| 5110 | ? RequiredTemplateKind(TemplateKWLoc) |
| 5111 | : TemplateNameIsRequired; |
| 5112 | if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS, |
| 5113 | RTK, nullptr, /*AllowTypoCorrection=*/false) && |
| 5114 | !R.isAmbiguous()) { |
| 5115 | if (LookupCtx) |
| 5116 | Diag(Name.getBeginLoc(), diag::err_no_member) |
| 5117 | << DNI.getName() << LookupCtx << SS.getRange(); |
| 5118 | else |
| 5119 | Diag(Name.getBeginLoc(), diag::err_undeclared_use) |
| 5120 | << DNI.getName() << SS.getRange(); |
| 5121 | } |
| 5122 | return TNK_Non_template; |
| 5123 | } |
| 5124 | |
| 5125 | NestedNameSpecifier *Qualifier = SS.getScopeRep(); |
| 5126 | |
| 5127 | switch (Name.getKind()) { |
| 5128 | case UnqualifiedIdKind::IK_Identifier: |
| 5129 | Result = TemplateTy::make( |
| 5130 | Context.getDependentTemplateName(Qualifier, Name.Identifier)); |
| 5131 | return TNK_Dependent_template_name; |
| 5132 | |
| 5133 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
| 5134 | Result = TemplateTy::make(Context.getDependentTemplateName( |
| 5135 | Qualifier, Name.OperatorFunctionId.Operator)); |
| 5136 | return TNK_Function_template; |
| 5137 | |
| 5138 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
| 5139 | // This is a kind of template name, but can never occur in a dependent |
| 5140 | // scope (literal operators can only be declared at namespace scope). |
| 5141 | break; |
| 5142 | |
| 5143 | default: |
| 5144 | break; |
| 5145 | } |
| 5146 | |
| 5147 | // This name cannot possibly name a dependent template. Diagnose this now |
| 5148 | // rather than building a dependent template name that can never be valid. |
| 5149 | Diag(Name.getBeginLoc(), |
| 5150 | diag::err_template_kw_refers_to_dependent_non_template) |
| 5151 | << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange() |
| 5152 | << TemplateKWLoc.isValid() << TemplateKWLoc; |
| 5153 | return TNK_Non_template; |
| 5154 | } |
| 5155 | |
| 5156 | bool Sema::CheckTemplateTypeArgument( |
| 5157 | TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL, |
| 5158 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
| 5159 | SmallVectorImpl<TemplateArgument> &CanonicalConverted) { |
| 5160 | const TemplateArgument &Arg = AL.getArgument(); |
| 5161 | QualType ArgType; |
| 5162 | TypeSourceInfo *TSI = nullptr; |
| 5163 | |
| 5164 | // Check template type parameter. |
| 5165 | switch(Arg.getKind()) { |
| 5166 | case TemplateArgument::Type: |
| 5167 | // C++ [temp.arg.type]p1: |
| 5168 | // A template-argument for a template-parameter which is a |
| 5169 | // type shall be a type-id. |
| 5170 | ArgType = Arg.getAsType(); |
| 5171 | TSI = AL.getTypeSourceInfo(); |
| 5172 | break; |
| 5173 | case TemplateArgument::Template: |
| 5174 | case TemplateArgument::TemplateExpansion: { |
| 5175 | // We have a template type parameter but the template argument |
| 5176 | // is a template without any arguments. |
| 5177 | SourceRange SR = AL.getSourceRange(); |
| 5178 | TemplateName Name = Arg.getAsTemplateOrTemplatePattern(); |
| 5179 | diagnoseMissingTemplateArguments(Name, SR.getEnd()); |
| 5180 | return true; |
| 5181 | } |
| 5182 | case TemplateArgument::Expression: { |
| 5183 | // We have a template type parameter but the template argument is an |
| 5184 | // expression; see if maybe it is missing the "typename" keyword. |
| 5185 | CXXScopeSpec SS; |
| 5186 | DeclarationNameInfo NameInfo; |
| 5187 | |
| 5188 | if (DependentScopeDeclRefExpr *ArgExpr = |
| 5189 | dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) { |
| 5190 | SS.Adopt(ArgExpr->getQualifierLoc()); |
| 5191 | NameInfo = ArgExpr->getNameInfo(); |
| 5192 | } else if (CXXDependentScopeMemberExpr *ArgExpr = |
| 5193 | dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) { |
| 5194 | if (ArgExpr->isImplicitAccess()) { |
| 5195 | SS.Adopt(ArgExpr->getQualifierLoc()); |
| 5196 | NameInfo = ArgExpr->getMemberNameInfo(); |
| 5197 | } |
| 5198 | } |
| 5199 | |
| 5200 | if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { |
| 5201 | LookupResult Result(*this, NameInfo, LookupOrdinaryName); |
| 5202 | LookupParsedName(Result, CurScope, &SS); |
| 5203 | |
| 5204 | if (Result.getAsSingle<TypeDecl>() || |
| 5205 | Result.getResultKind() == |
| 5206 | LookupResult::NotFoundInCurrentInstantiation) { |
| 5207 | assert(SS.getScopeRep() && "dependent scope expr must has a scope!")(static_cast <bool> (SS.getScopeRep() && "dependent scope expr must has a scope!" ) ? void (0) : __assert_fail ("SS.getScopeRep() && \"dependent scope expr must has a scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 5207, __extension__ __PRETTY_FUNCTION__ )); |
| 5208 | // Suggest that the user add 'typename' before the NNS. |
| 5209 | SourceLocation Loc = AL.getSourceRange().getBegin(); |
| 5210 | Diag(Loc, getLangOpts().MSVCCompat |
| 5211 | ? diag::ext_ms_template_type_arg_missing_typename |
| 5212 | : diag::err_template_arg_must_be_type_suggest) |
| 5213 | << FixItHint::CreateInsertion(Loc, "typename "); |
| 5214 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 5215 | |
| 5216 | // Recover by synthesizing a type using the location information that we |
| 5217 | // already have. |
| 5218 | ArgType = |
| 5219 | Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II); |
| 5220 | TypeLocBuilder TLB; |
| 5221 | DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType); |
| 5222 | TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/)); |
| 5223 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 5224 | TL.setNameLoc(NameInfo.getLoc()); |
| 5225 | TSI = TLB.getTypeSourceInfo(Context, ArgType); |
| 5226 | |
| 5227 | // Overwrite our input TemplateArgumentLoc so that we can recover |
| 5228 | // properly. |
| 5229 | AL = TemplateArgumentLoc(TemplateArgument(ArgType), |
| 5230 | TemplateArgumentLocInfo(TSI)); |
| 5231 | |
| 5232 | break; |
| 5233 | } |
| 5234 | } |
| 5235 | // fallthrough |
| 5236 | [[fallthrough]]; |
| 5237 | } |
| 5238 | default: { |
| 5239 | // We have a template type parameter but the template argument |
| 5240 | // is not a type. |
| 5241 | SourceRange SR = AL.getSourceRange(); |
| 5242 | Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; |
| 5243 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 5244 | |
| 5245 | return true; |
| 5246 | } |
| 5247 | } |
| 5248 | |
| 5249 | if (CheckTemplateArgument(TSI)) |
| 5250 | return true; |
| 5251 | |
| 5252 | // Objective-C ARC: |
| 5253 | // If an explicitly-specified template argument type is a lifetime type |
| 5254 | // with no lifetime qualifier, the __strong lifetime qualifier is inferred. |
| 5255 | if (getLangOpts().ObjCAutoRefCount && |
| 5256 | ArgType->isObjCLifetimeType() && |
| 5257 | !ArgType.getObjCLifetime()) { |
| 5258 | Qualifiers Qs; |
| 5259 | Qs.setObjCLifetime(Qualifiers::OCL_Strong); |
| 5260 | ArgType = Context.getQualifiedType(ArgType, Qs); |
| 5261 | } |
| 5262 | |
| 5263 | SugaredConverted.push_back(TemplateArgument(ArgType)); |
| 5264 | CanonicalConverted.push_back( |
| 5265 | TemplateArgument(Context.getCanonicalType(ArgType))); |
| 5266 | return false; |
| 5267 | } |
| 5268 | |
| 5269 | /// Substitute template arguments into the default template argument for |
| 5270 | /// the given template type parameter. |
| 5271 | /// |
| 5272 | /// \param SemaRef the semantic analysis object for which we are performing |
| 5273 | /// the substitution. |
| 5274 | /// |
| 5275 | /// \param Template the template that we are synthesizing template arguments |
| 5276 | /// for. |
| 5277 | /// |
| 5278 | /// \param TemplateLoc the location of the template name that started the |
| 5279 | /// template-id we are checking. |
| 5280 | /// |
| 5281 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
| 5282 | /// terminates the template-id. |
| 5283 | /// |
| 5284 | /// \param Param the template template parameter whose default we are |
| 5285 | /// substituting into. |
| 5286 | /// |
| 5287 | /// \param Converted the list of template arguments provided for template |
| 5288 | /// parameters that precede \p Param in the template parameter list. |
| 5289 | /// \returns the substituted template argument, or NULL if an error occurred. |
| 5290 | static TypeSourceInfo *SubstDefaultTemplateArgument( |
| 5291 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
| 5292 | SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, |
| 5293 | ArrayRef<TemplateArgument> SugaredConverted, |
| 5294 | ArrayRef<TemplateArgument> CanonicalConverted) { |
| 5295 | TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); |
| 5296 | |
| 5297 | // If the argument type is dependent, instantiate it now based |
| 5298 | // on the previously-computed template arguments. |
| 5299 | if (ArgType->getType()->isInstantiationDependentType()) { |
| 5300 | Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, |
| 5301 | SugaredConverted, |
| 5302 | SourceRange(TemplateLoc, RAngleLoc)); |
| 5303 | if (Inst.isInvalid()) |
| 5304 | return nullptr; |
| 5305 | |
| 5306 | // Only substitute for the innermost template argument list. |
| 5307 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
| 5308 | /*Final=*/true); |
| 5309 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
| 5310 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
| 5311 | |
| 5312 | bool ForLambdaCallOperator = false; |
| 5313 | if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext())) |
| 5314 | ForLambdaCallOperator = Rec->isLambda(); |
| 5315 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(), |
| 5316 | !ForLambdaCallOperator); |
| 5317 | ArgType = |
| 5318 | SemaRef.SubstType(ArgType, TemplateArgLists, |
| 5319 | Param->getDefaultArgumentLoc(), Param->getDeclName()); |
| 5320 | } |
| 5321 | |
| 5322 | return ArgType; |
| 5323 | } |
| 5324 | |
| 5325 | /// Substitute template arguments into the default template argument for |
| 5326 | /// the given non-type template parameter. |
| 5327 | /// |
| 5328 | /// \param SemaRef the semantic analysis object for which we are performing |
| 5329 | /// the substitution. |
| 5330 | /// |
| 5331 | /// \param Template the template that we are synthesizing template arguments |
| 5332 | /// for. |
| 5333 | /// |
| 5334 | /// \param TemplateLoc the location of the template name that started the |
| 5335 | /// template-id we are checking. |
| 5336 | /// |
| 5337 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
| 5338 | /// terminates the template-id. |
| 5339 | /// |
| 5340 | /// \param Param the non-type template parameter whose default we are |
| 5341 | /// substituting into. |
| 5342 | /// |
| 5343 | /// \param Converted the list of template arguments provided for template |
| 5344 | /// parameters that precede \p Param in the template parameter list. |
| 5345 | /// |
| 5346 | /// \returns the substituted template argument, or NULL if an error occurred. |
| 5347 | static ExprResult SubstDefaultTemplateArgument( |
| 5348 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
| 5349 | SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param, |
| 5350 | ArrayRef<TemplateArgument> SugaredConverted, |
| 5351 | ArrayRef<TemplateArgument> CanonicalConverted) { |
| 5352 | Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, |
| 5353 | SugaredConverted, |
| 5354 | SourceRange(TemplateLoc, RAngleLoc)); |
| 5355 | if (Inst.isInvalid()) |
| 5356 | return ExprError(); |
| 5357 | |
| 5358 | // Only substitute for the innermost template argument list. |
| 5359 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
| 5360 | /*Final=*/true); |
| 5361 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
| 5362 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
| 5363 | |
| 5364 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); |
| 5365 | EnterExpressionEvaluationContext ConstantEvaluated( |
| 5366 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
| 5367 | return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists); |
| 5368 | } |
| 5369 | |
| 5370 | /// Substitute template arguments into the default template argument for |
| 5371 | /// the given template template parameter. |
| 5372 | /// |
| 5373 | /// \param SemaRef the semantic analysis object for which we are performing |
| 5374 | /// the substitution. |
| 5375 | /// |
| 5376 | /// \param Template the template that we are synthesizing template arguments |
| 5377 | /// for. |
| 5378 | /// |
| 5379 | /// \param TemplateLoc the location of the template name that started the |
| 5380 | /// template-id we are checking. |
| 5381 | /// |
| 5382 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
| 5383 | /// terminates the template-id. |
| 5384 | /// |
| 5385 | /// \param Param the template template parameter whose default we are |
| 5386 | /// substituting into. |
| 5387 | /// |
| 5388 | /// \param Converted the list of template arguments provided for template |
| 5389 | /// parameters that precede \p Param in the template parameter list. |
| 5390 | /// |
| 5391 | /// \param QualifierLoc Will be set to the nested-name-specifier (with |
| 5392 | /// source-location information) that precedes the template name. |
| 5393 | /// |
| 5394 | /// \returns the substituted template argument, or NULL if an error occurred. |
| 5395 | static TemplateName SubstDefaultTemplateArgument( |
| 5396 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
| 5397 | SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param, |
| 5398 | ArrayRef<TemplateArgument> SugaredConverted, |
| 5399 | ArrayRef<TemplateArgument> CanonicalConverted, |
| 5400 | NestedNameSpecifierLoc &QualifierLoc) { |
| 5401 | Sema::InstantiatingTemplate Inst( |
| 5402 | SemaRef, TemplateLoc, TemplateParameter(Param), Template, |
| 5403 | SugaredConverted, SourceRange(TemplateLoc, RAngleLoc)); |
| 5404 | if (Inst.isInvalid()) |
| 5405 | return TemplateName(); |
| 5406 | |
| 5407 | // Only substitute for the innermost template argument list. |
| 5408 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
| 5409 | /*Final=*/true); |
| 5410 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
| 5411 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
| 5412 | |
| 5413 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); |
| 5414 | // Substitute into the nested-name-specifier first, |
| 5415 | QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); |
| 5416 | if (QualifierLoc) { |
| 5417 | QualifierLoc = |
| 5418 | SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists); |
| 5419 | if (!QualifierLoc) |
| 5420 | return TemplateName(); |
| 5421 | } |
| 5422 | |
| 5423 | return SemaRef.SubstTemplateName( |
| 5424 | QualifierLoc, |
| 5425 | Param->getDefaultArgument().getArgument().getAsTemplate(), |
| 5426 | Param->getDefaultArgument().getTemplateNameLoc(), |
| 5427 | TemplateArgLists); |
| 5428 | } |
| 5429 | |
| 5430 | /// If the given template parameter has a default template |
| 5431 | /// argument, substitute into that default template argument and |
| 5432 | /// return the corresponding template argument. |
| 5433 | TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable( |
| 5434 | TemplateDecl *Template, SourceLocation TemplateLoc, |
| 5435 | SourceLocation RAngleLoc, Decl *Param, |
| 5436 | ArrayRef<TemplateArgument> SugaredConverted, |
| 5437 | ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) { |
| 5438 | HasDefaultArg = false; |
| 5439 | |
| 5440 | if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { |
| 5441 | if (!hasReachableDefaultArgument(TypeParm)) |
| 5442 | return TemplateArgumentLoc(); |
| 5443 | |
| 5444 | HasDefaultArg = true; |
| 5445 | TypeSourceInfo *DI = SubstDefaultTemplateArgument( |
| 5446 | *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted, |
| 5447 | CanonicalConverted); |
| 5448 | if (DI) |
| 5449 | return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); |
| 5450 | |
| 5451 | return TemplateArgumentLoc(); |
| 5452 | } |
| 5453 | |
| 5454 | if (NonTypeTemplateParmDecl *NonTypeParm |
| 5455 | = dyn_cast<NonTypeTemplateParmDecl>(Param)) { |
| 5456 | if (!hasReachableDefaultArgument(NonTypeParm)) |
| 5457 | return TemplateArgumentLoc(); |
| 5458 | |
| 5459 | HasDefaultArg = true; |
| 5460 | ExprResult Arg = SubstDefaultTemplateArgument( |
| 5461 | *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted, |
| 5462 | CanonicalConverted); |
| 5463 | if (Arg.isInvalid()) |
| 5464 | return TemplateArgumentLoc(); |
| 5465 | |
| 5466 | Expr *ArgE = Arg.getAs<Expr>(); |
| 5467 | return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); |
| 5468 | } |
| 5469 | |
| 5470 | TemplateTemplateParmDecl *TempTempParm |
| 5471 | = cast<TemplateTemplateParmDecl>(Param); |
| 5472 | if (!hasReachableDefaultArgument(TempTempParm)) |
| 5473 | return TemplateArgumentLoc(); |
| 5474 | |
| 5475 | HasDefaultArg = true; |
| 5476 | NestedNameSpecifierLoc QualifierLoc; |
| 5477 | TemplateName TName = SubstDefaultTemplateArgument( |
| 5478 | *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted, |
| 5479 | CanonicalConverted, QualifierLoc); |
| 5480 | if (TName.isNull()) |
| 5481 | return TemplateArgumentLoc(); |
| 5482 | |
| 5483 | return TemplateArgumentLoc( |
| 5484 | Context, TemplateArgument(TName), |
| 5485 | TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), |
| 5486 | TempTempParm->getDefaultArgument().getTemplateNameLoc()); |
| 5487 | } |
| 5488 | |
| 5489 | /// Convert a template-argument that we parsed as a type into a template, if |
| 5490 | /// possible. C++ permits injected-class-names to perform dual service as |
| 5491 | /// template template arguments and as template type arguments. |
| 5492 | static TemplateArgumentLoc |
| 5493 | convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) { |
| 5494 | // Extract and step over any surrounding nested-name-specifier. |
| 5495 | NestedNameSpecifierLoc QualLoc; |
| 5496 | if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) { |
| 5497 | if (ETLoc.getTypePtr()->getKeyword() != ETK_None) |
| 5498 | return TemplateArgumentLoc(); |
| 5499 | |
| 5500 | QualLoc = ETLoc.getQualifierLoc(); |
| 5501 | TLoc = ETLoc.getNamedTypeLoc(); |
| 5502 | } |
| 5503 | // If this type was written as an injected-class-name, it can be used as a |
| 5504 | // template template argument. |
| 5505 | if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>()) |
| 5506 | return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(), |
| 5507 | QualLoc, InjLoc.getNameLoc()); |
| 5508 | |
| 5509 | // If this type was written as an injected-class-name, it may have been |
| 5510 | // converted to a RecordType during instantiation. If the RecordType is |
| 5511 | // *not* wrapped in a TemplateSpecializationType and denotes a class |
| 5512 | // template specialization, it must have come from an injected-class-name. |
| 5513 | if (auto RecLoc = TLoc.getAs<RecordTypeLoc>()) |
| 5514 | if (auto *CTSD = |
| 5515 | dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl())) |
| 5516 | return TemplateArgumentLoc(Context, |
| 5517 | TemplateName(CTSD->getSpecializedTemplate()), |
| 5518 | QualLoc, RecLoc.getNameLoc()); |
| 5519 | |
| 5520 | return TemplateArgumentLoc(); |
| 5521 | } |
| 5522 | |
| 5523 | /// Check that the given template argument corresponds to the given |
| 5524 | /// template parameter. |
| 5525 | /// |
| 5526 | /// \param Param The template parameter against which the argument will be |
| 5527 | /// checked. |
| 5528 | /// |
| 5529 | /// \param Arg The template argument, which may be updated due to conversions. |
| 5530 | /// |
| 5531 | /// \param Template The template in which the template argument resides. |
| 5532 | /// |
| 5533 | /// \param TemplateLoc The location of the template name for the template |
| 5534 | /// whose argument list we're matching. |
| 5535 | /// |
| 5536 | /// \param RAngleLoc The location of the right angle bracket ('>') that closes |
| 5537 | /// the template argument list. |
| 5538 | /// |
| 5539 | /// \param ArgumentPackIndex The index into the argument pack where this |
| 5540 | /// argument will be placed. Only valid if the parameter is a parameter pack. |
| 5541 | /// |
| 5542 | /// \param Converted The checked, converted argument will be added to the |
| 5543 | /// end of this small vector. |
| 5544 | /// |
| 5545 | /// \param CTAK Describes how we arrived at this particular template argument: |
| 5546 | /// explicitly written, deduced, etc. |
| 5547 | /// |
| 5548 | /// \returns true on error, false otherwise. |
| 5549 | bool Sema::CheckTemplateArgument( |
| 5550 | NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, |
| 5551 | SourceLocation TemplateLoc, SourceLocation RAngleLoc, |
| 5552 | unsigned ArgumentPackIndex, |
| 5553 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
| 5554 | SmallVectorImpl<TemplateArgument> &CanonicalConverted, |
| 5555 | CheckTemplateArgumentKind CTAK) { |
| 5556 | // Check template type parameters. |
| 5557 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) |
| 5558 | return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted, |
| 5559 | CanonicalConverted); |
| 5560 | |
| 5561 | // Check non-type template parameters. |
| 5562 | if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { |
| 5563 | // Do substitution on the type of the non-type template parameter |
| 5564 | // with the template arguments we've seen thus far. But if the |
| 5565 | // template has a dependent context then we cannot substitute yet. |
| 5566 | QualType NTTPType = NTTP->getType(); |
| 5567 | if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) |
| 5568 | NTTPType = NTTP->getExpansionType(ArgumentPackIndex); |
| 5569 | |
| 5570 | if (NTTPType->isInstantiationDependentType() && |
| 5571 | !isa<TemplateTemplateParmDecl>(Template) && |
| 5572 | !Template->getDeclContext()->isDependentContext()) { |
| 5573 | // Do substitution on the type of the non-type template parameter. |
| 5574 | InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP, |
| 5575 | SugaredConverted, |
| 5576 | SourceRange(TemplateLoc, RAngleLoc)); |
| 5577 | if (Inst.isInvalid()) |
| 5578 | return true; |
| 5579 | |
| 5580 | MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted, |
| 5581 | /*Final=*/true); |
| 5582 | // If the parameter is a pack expansion, expand this slice of the pack. |
| 5583 | if (auto *PET = NTTPType->getAs<PackExpansionType>()) { |
| 5584 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, |
| 5585 | ArgumentPackIndex); |
| 5586 | NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(), |
| 5587 | NTTP->getDeclName()); |
| 5588 | } else { |
| 5589 | NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(), |
| 5590 | NTTP->getDeclName()); |
| 5591 | } |
| 5592 | |
| 5593 | // If that worked, check the non-type template parameter type |
| 5594 | // for validity. |
| 5595 | if (!NTTPType.isNull()) |
| 5596 | NTTPType = CheckNonTypeTemplateParameterType(NTTPType, |
| 5597 | NTTP->getLocation()); |
| 5598 | if (NTTPType.isNull()) |
| 5599 | return true; |
| 5600 | } |
| 5601 | |
| 5602 | switch (Arg.getArgument().getKind()) { |
| 5603 | case TemplateArgument::Null: |
| 5604 | llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here" , "clang/lib/Sema/SemaTemplate.cpp", 5604); |
| 5605 | |
| 5606 | case TemplateArgument::Expression: { |
| 5607 | Expr *E = Arg.getArgument().getAsExpr(); |
| 5608 | TemplateArgument SugaredResult, CanonicalResult; |
| 5609 | unsigned CurSFINAEErrors = NumSFINAEErrors; |
| 5610 | ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult, |
| 5611 | CanonicalResult, CTAK); |
| 5612 | if (Res.isInvalid()) |
| 5613 | return true; |
| 5614 | // If the current template argument causes an error, give up now. |
| 5615 | if (CurSFINAEErrors < NumSFINAEErrors) |
| 5616 | return true; |
| 5617 | |
| 5618 | // If the resulting expression is new, then use it in place of the |
| 5619 | // old expression in the template argument. |
| 5620 | if (Res.get() != E) { |
| 5621 | TemplateArgument TA(Res.get()); |
| 5622 | Arg = TemplateArgumentLoc(TA, Res.get()); |
| 5623 | } |
| 5624 | |
| 5625 | SugaredConverted.push_back(SugaredResult); |
| 5626 | CanonicalConverted.push_back(CanonicalResult); |
| 5627 | break; |
| 5628 | } |
| 5629 | |
| 5630 | case TemplateArgument::Declaration: |
| 5631 | case TemplateArgument::Integral: |
| 5632 | case TemplateArgument::NullPtr: |
| 5633 | // We've already checked this template argument, so just copy |
| 5634 | // it to the list of converted arguments. |
| 5635 | SugaredConverted.push_back(Arg.getArgument()); |
| 5636 | CanonicalConverted.push_back( |
| 5637 | Context.getCanonicalTemplateArgument(Arg.getArgument())); |
| 5638 | break; |
| 5639 | |
| 5640 | case TemplateArgument::Template: |
| 5641 | case TemplateArgument::TemplateExpansion: |
| 5642 | // We were given a template template argument. It may not be ill-formed; |
| 5643 | // see below. |
| 5644 | if (DependentTemplateName *DTN |
| 5645 | = Arg.getArgument().getAsTemplateOrTemplatePattern() |
| 5646 | .getAsDependentTemplateName()) { |
| 5647 | // We have a template argument such as \c T::template X, which we |
| 5648 | // parsed as a template template argument. However, since we now |
| 5649 | // know that we need a non-type template argument, convert this |
| 5650 | // template name into an expression. |
| 5651 | |
| 5652 | DeclarationNameInfo NameInfo(DTN->getIdentifier(), |
| 5653 | Arg.getTemplateNameLoc()); |
| 5654 | |
| 5655 | CXXScopeSpec SS; |
| 5656 | SS.Adopt(Arg.getTemplateQualifierLoc()); |
| 5657 | // FIXME: the template-template arg was a DependentTemplateName, |
| 5658 | // so it was provided with a template keyword. However, its source |
| 5659 | // location is not stored in the template argument structure. |
| 5660 | SourceLocation TemplateKWLoc; |
| 5661 | ExprResult E = DependentScopeDeclRefExpr::Create( |
| 5662 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, |
| 5663 | nullptr); |
| 5664 | |
| 5665 | // If we parsed the template argument as a pack expansion, create a |
| 5666 | // pack expansion expression. |
| 5667 | if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ |
| 5668 | E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc()); |
| 5669 | if (E.isInvalid()) |
| 5670 | return true; |
| 5671 | } |
| 5672 | |
| 5673 | TemplateArgument SugaredResult, CanonicalResult; |
| 5674 | E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult, |
| 5675 | CanonicalResult, CTAK_Specified); |
| 5676 | if (E.isInvalid()) |
| 5677 | return true; |
| 5678 | |
| 5679 | SugaredConverted.push_back(SugaredResult); |
| 5680 | CanonicalConverted.push_back(CanonicalResult); |
| 5681 | break; |
| 5682 | } |
| 5683 | |
| 5684 | // We have a template argument that actually does refer to a class |
| 5685 | // template, alias template, or template template parameter, and |
| 5686 | // therefore cannot be a non-type template argument. |
| 5687 | Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) |
| 5688 | << Arg.getSourceRange(); |
| 5689 | |
| 5690 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 5691 | return true; |
| 5692 | |
| 5693 | case TemplateArgument::Type: { |
| 5694 | // We have a non-type template parameter but the template |
| 5695 | // argument is a type. |
| 5696 | |
| 5697 | // C++ [temp.arg]p2: |
| 5698 | // In a template-argument, an ambiguity between a type-id and |
| 5699 | // an expression is resolved to a type-id, regardless of the |
| 5700 | // form of the corresponding template-parameter. |
| 5701 | // |
| 5702 | // We warn specifically about this case, since it can be rather |
| 5703 | // confusing for users. |
| 5704 | QualType T = Arg.getArgument().getAsType(); |
| 5705 | SourceRange SR = Arg.getSourceRange(); |
| 5706 | if (T->isFunctionType()) |
| 5707 | Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; |
| 5708 | else |
| 5709 | Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; |
| 5710 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 5711 | return true; |
| 5712 | } |
| 5713 | |
| 5714 | case TemplateArgument::Pack: |
| 5715 | llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs" , "clang/lib/Sema/SemaTemplate.cpp", 5715); |
| 5716 | } |
| 5717 | |
| 5718 | return false; |
| 5719 | } |
| 5720 | |
| 5721 | |
| 5722 | // Check template template parameters. |
| 5723 | TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); |
| 5724 | |
| 5725 | TemplateParameterList *Params = TempParm->getTemplateParameters(); |
| 5726 | if (TempParm->isExpandedParameterPack()) |
| 5727 | Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex); |
| 5728 | |
| 5729 | // Substitute into the template parameter list of the template |
| 5730 | // template parameter, since previously-supplied template arguments |
| 5731 | // may appear within the template template parameter. |
| 5732 | // |
| 5733 | // FIXME: Skip this if the parameters aren't instantiation-dependent. |
| 5734 | { |
| 5735 | // Set up a template instantiation context. |
| 5736 | LocalInstantiationScope Scope(*this); |
| 5737 | InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm, |
| 5738 | SugaredConverted, |
| 5739 | SourceRange(TemplateLoc, RAngleLoc)); |
| 5740 | if (Inst.isInvalid()) |
| 5741 | return true; |
| 5742 | |
| 5743 | Params = |
| 5744 | SubstTemplateParams(Params, CurContext, |
| 5745 | MultiLevelTemplateArgumentList( |
| 5746 | Template, SugaredConverted, /*Final=*/true), |
| 5747 | /*EvaluateConstraints=*/false); |
| 5748 | if (!Params) |
| 5749 | return true; |
| 5750 | } |
| 5751 | |
| 5752 | // C++1z [temp.local]p1: (DR1004) |
| 5753 | // When [the injected-class-name] is used [...] as a template-argument for |
| 5754 | // a template template-parameter [...] it refers to the class template |
| 5755 | // itself. |
| 5756 | if (Arg.getArgument().getKind() == TemplateArgument::Type) { |
| 5757 | TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate( |
| 5758 | Context, Arg.getTypeSourceInfo()->getTypeLoc()); |
| 5759 | if (!ConvertedArg.getArgument().isNull()) |
| 5760 | Arg = ConvertedArg; |
| 5761 | } |
| 5762 | |
| 5763 | switch (Arg.getArgument().getKind()) { |
| 5764 | case TemplateArgument::Null: |
| 5765 | llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here" , "clang/lib/Sema/SemaTemplate.cpp", 5765); |
| 5766 | |
| 5767 | case TemplateArgument::Template: |
| 5768 | case TemplateArgument::TemplateExpansion: |
| 5769 | if (CheckTemplateTemplateArgument(TempParm, Params, Arg)) |
| 5770 | return true; |
| 5771 | |
| 5772 | SugaredConverted.push_back(Arg.getArgument()); |
| 5773 | CanonicalConverted.push_back( |
| 5774 | Context.getCanonicalTemplateArgument(Arg.getArgument())); |
| 5775 | break; |
| 5776 | |
| 5777 | case TemplateArgument::Expression: |
| 5778 | case TemplateArgument::Type: |
| 5779 | // We have a template template parameter but the template |
| 5780 | // argument does not refer to a template. |
| 5781 | Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) |
| 5782 | << getLangOpts().CPlusPlus11; |
| 5783 | return true; |
| 5784 | |
| 5785 | case TemplateArgument::Declaration: |
| 5786 | llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter" , "clang/lib/Sema/SemaTemplate.cpp", 5786); |
| 5787 | case TemplateArgument::Integral: |
| 5788 | llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter" , "clang/lib/Sema/SemaTemplate.cpp", 5788); |
| 5789 | case TemplateArgument::NullPtr: |
| 5790 | llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter" , "clang/lib/Sema/SemaTemplate.cpp", 5790); |
| 5791 | |
| 5792 | case TemplateArgument::Pack: |
| 5793 | llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs" , "clang/lib/Sema/SemaTemplate.cpp", 5793); |
| 5794 | } |
| 5795 | |
| 5796 | return false; |
| 5797 | } |
| 5798 | |
| 5799 | /// Diagnose a missing template argument. |
| 5800 | template<typename TemplateParmDecl> |
| 5801 | static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, |
| 5802 | TemplateDecl *TD, |
| 5803 | const TemplateParmDecl *D, |
| 5804 | TemplateArgumentListInfo &Args) { |
| 5805 | // Dig out the most recent declaration of the template parameter; there may be |
| 5806 | // declarations of the template that are more recent than TD. |
| 5807 | D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl()) |
| 5808 | ->getTemplateParameters() |
| 5809 | ->getParam(D->getIndex())); |
| 5810 | |
| 5811 | // If there's a default argument that's not reachable, diagnose that we're |
| 5812 | // missing a module import. |
| 5813 | llvm::SmallVector<Module*, 8> Modules; |
| 5814 | if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) { |
| 5815 | S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD), |
| 5816 | D->getDefaultArgumentLoc(), Modules, |
| 5817 | Sema::MissingImportKind::DefaultArgument, |
| 5818 | /*Recover*/true); |
| 5819 | return true; |
| 5820 | } |
| 5821 | |
| 5822 | // FIXME: If there's a more recent default argument that *is* visible, |
| 5823 | // diagnose that it was declared too late. |
| 5824 | |
| 5825 | TemplateParameterList *Params = TD->getTemplateParameters(); |
| 5826 | |
| 5827 | S.Diag(Loc, diag::err_template_arg_list_different_arity) |
| 5828 | << /*not enough args*/0 |
| 5829 | << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD)) |
| 5830 | << TD; |
| 5831 | S.Diag(TD->getLocation(), diag::note_template_decl_here) |
| 5832 | << Params->getSourceRange(); |
| 5833 | return true; |
| 5834 | } |
| 5835 | |
| 5836 | /// Check that the given template argument list is well-formed |
| 5837 | /// for specializing the given template. |
| 5838 | bool Sema::CheckTemplateArgumentList( |
| 5839 | TemplateDecl *Template, SourceLocation TemplateLoc, |
| 5840 | TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, |
| 5841 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
| 5842 | SmallVectorImpl<TemplateArgument> &CanonicalConverted, |
| 5843 | bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) { |
| 5844 | |
| 5845 | if (ConstraintsNotSatisfied) |
| 5846 | *ConstraintsNotSatisfied = false; |
| 5847 | |
| 5848 | // Make a copy of the template arguments for processing. Only make the |
| 5849 | // changes at the end when successful in matching the arguments to the |
| 5850 | // template. |
| 5851 | TemplateArgumentListInfo NewArgs = TemplateArgs; |
| 5852 | |
| 5853 | // Make sure we get the template parameter list from the most |
| 5854 | // recent declaration, since that is the only one that is guaranteed to |
| 5855 | // have all the default template argument information. |
| 5856 | TemplateParameterList *Params = |
| 5857 | cast<TemplateDecl>(Template->getMostRecentDecl()) |
| 5858 | ->getTemplateParameters(); |
| 5859 | |
| 5860 | SourceLocation RAngleLoc = NewArgs.getRAngleLoc(); |
| 5861 | |
| 5862 | // C++ [temp.arg]p1: |
| 5863 | // [...] The type and form of each template-argument specified in |
| 5864 | // a template-id shall match the type and form specified for the |
| 5865 | // corresponding parameter declared by the template in its |
| 5866 | // template-parameter-list. |
| 5867 | bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); |
| 5868 | SmallVector<TemplateArgument, 2> SugaredArgumentPack; |
| 5869 | SmallVector<TemplateArgument, 2> CanonicalArgumentPack; |
| 5870 | unsigned ArgIdx = 0, NumArgs = NewArgs.size(); |
| 5871 | LocalInstantiationScope InstScope(*this, true); |
| 5872 | for (TemplateParameterList::iterator Param = Params->begin(), |
| 5873 | ParamEnd = Params->end(); |
| 5874 | Param != ParamEnd; /* increment in loop */) { |
| 5875 | // If we have an expanded parameter pack, make sure we don't have too |
| 5876 | // many arguments. |
| 5877 | if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) { |
| 5878 | if (*Expansions == SugaredArgumentPack.size()) { |
| 5879 | // We're done with this parameter pack. Pack up its arguments and add |
| 5880 | // them to the list. |
| 5881 | SugaredConverted.push_back( |
| 5882 | TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); |
| 5883 | SugaredArgumentPack.clear(); |
| 5884 | |
| 5885 | CanonicalConverted.push_back( |
| 5886 | TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); |
| 5887 | CanonicalArgumentPack.clear(); |
| 5888 | |
| 5889 | // This argument is assigned to the next parameter. |
| 5890 | ++Param; |
| 5891 | continue; |
| 5892 | } else if (ArgIdx == NumArgs && !PartialTemplateArgs) { |
| 5893 | // Not enough arguments for this parameter pack. |
| 5894 | Diag(TemplateLoc, diag::err_template_arg_list_different_arity) |
| 5895 | << /*not enough args*/0 |
| 5896 | << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) |
| 5897 | << Template; |
| 5898 | Diag(Template->getLocation(), diag::note_template_decl_here) |
| 5899 | << Params->getSourceRange(); |
| 5900 | return true; |
| 5901 | } |
| 5902 | } |
| 5903 | |
| 5904 | if (ArgIdx < NumArgs) { |
| 5905 | // Check the template argument we were given. |
| 5906 | if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc, |
| 5907 | RAngleLoc, SugaredArgumentPack.size(), |
| 5908 | SugaredConverted, CanonicalConverted, |
| 5909 | CTAK_Specified)) |
| 5910 | return true; |
| 5911 | |
| 5912 | CanonicalConverted.back().setIsDefaulted( |
| 5913 | clang::isSubstitutedDefaultArgument( |
| 5914 | Context, NewArgs[ArgIdx].getArgument(), *Param, |
| 5915 | CanonicalConverted, Params->getDepth())); |
| 5916 | |
| 5917 | bool PackExpansionIntoNonPack = |
| 5918 | NewArgs[ArgIdx].getArgument().isPackExpansion() && |
| 5919 | (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param)); |
| 5920 | if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) || |
| 5921 | isa<ConceptDecl>(Template))) { |
| 5922 | // Core issue 1430: we have a pack expansion as an argument to an |
| 5923 | // alias template, and it's not part of a parameter pack. This |
| 5924 | // can't be canonicalized, so reject it now. |
| 5925 | // As for concepts - we cannot normalize constraints where this |
| 5926 | // situation exists. |
| 5927 | Diag(NewArgs[ArgIdx].getLocation(), |
| 5928 | diag::err_template_expansion_into_fixed_list) |
| 5929 | << (isa<ConceptDecl>(Template) ? 1 : 0) |
| 5930 | << NewArgs[ArgIdx].getSourceRange(); |
| 5931 | Diag((*Param)->getLocation(), diag::note_template_param_here); |
| 5932 | return true; |
| 5933 | } |
| 5934 | |
| 5935 | // We're now done with this argument. |
| 5936 | ++ArgIdx; |
| 5937 | |
| 5938 | if ((*Param)->isTemplateParameterPack()) { |
| 5939 | // The template parameter was a template parameter pack, so take the |
| 5940 | // deduced argument and place it on the argument pack. Note that we |
| 5941 | // stay on the same template parameter so that we can deduce more |
| 5942 | // arguments. |
| 5943 | SugaredArgumentPack.push_back(SugaredConverted.pop_back_val()); |
| 5944 | CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val()); |
| 5945 | } else { |
| 5946 | // Move to the next template parameter. |
| 5947 | ++Param; |
| 5948 | } |
| 5949 | |
| 5950 | // If we just saw a pack expansion into a non-pack, then directly convert |
| 5951 | // the remaining arguments, because we don't know what parameters they'll |
| 5952 | // match up with. |
| 5953 | if (PackExpansionIntoNonPack) { |
| 5954 | if (!SugaredArgumentPack.empty()) { |
| 5955 | // If we were part way through filling in an expanded parameter pack, |
| 5956 | // fall back to just producing individual arguments. |
| 5957 | SugaredConverted.insert(SugaredConverted.end(), |
| 5958 | SugaredArgumentPack.begin(), |
| 5959 | SugaredArgumentPack.end()); |
| 5960 | SugaredArgumentPack.clear(); |
| 5961 | |
| 5962 | CanonicalConverted.insert(CanonicalConverted.end(), |
| 5963 | CanonicalArgumentPack.begin(), |
| 5964 | CanonicalArgumentPack.end()); |
| 5965 | CanonicalArgumentPack.clear(); |
| 5966 | } |
| 5967 | |
| 5968 | while (ArgIdx < NumArgs) { |
| 5969 | const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument(); |
| 5970 | SugaredConverted.push_back(Arg); |
| 5971 | CanonicalConverted.push_back( |
| 5972 | Context.getCanonicalTemplateArgument(Arg)); |
| 5973 | ++ArgIdx; |
| 5974 | } |
| 5975 | |
| 5976 | return false; |
| 5977 | } |
| 5978 | |
| 5979 | continue; |
| 5980 | } |
| 5981 | |
| 5982 | // If we're checking a partial template argument list, we're done. |
| 5983 | if (PartialTemplateArgs) { |
| 5984 | if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) { |
| 5985 | SugaredConverted.push_back( |
| 5986 | TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); |
| 5987 | CanonicalConverted.push_back( |
| 5988 | TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); |
| 5989 | } |
| 5990 | return false; |
| 5991 | } |
| 5992 | |
| 5993 | // If we have a template parameter pack with no more corresponding |
| 5994 | // arguments, just break out now and we'll fill in the argument pack below. |
| 5995 | if ((*Param)->isTemplateParameterPack()) { |
| 5996 | assert(!getExpandedPackSize(*Param) &&(static_cast <bool> (!getExpandedPackSize(*Param) && "Should have dealt with this already") ? void (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\"" , "clang/lib/Sema/SemaTemplate.cpp", 5997, __extension__ __PRETTY_FUNCTION__ )) |
| 5997 | "Should have dealt with this already")(static_cast <bool> (!getExpandedPackSize(*Param) && "Should have dealt with this already") ? void (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\"" , "clang/lib/Sema/SemaTemplate.cpp", 5997, __extension__ __PRETTY_FUNCTION__ )); |
| 5998 | |
| 5999 | // A non-expanded parameter pack before the end of the parameter list |
| 6000 | // only occurs for an ill-formed template parameter list, unless we've |
| 6001 | // got a partial argument list for a function template, so just bail out. |
| 6002 | if (Param + 1 != ParamEnd) { |
| 6003 | assert((static_cast <bool> ((Template->getMostRecentDecl()-> getKind() != Decl::Kind::Concept) && "Concept templates must have parameter packs at the end." ) ? void (0) : __assert_fail ("(Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) && \"Concept templates must have parameter packs at the end.\"" , "clang/lib/Sema/SemaTemplate.cpp", 6005, __extension__ __PRETTY_FUNCTION__ )) |
| 6004 | (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&(static_cast <bool> ((Template->getMostRecentDecl()-> getKind() != Decl::Kind::Concept) && "Concept templates must have parameter packs at the end." ) ? void (0) : __assert_fail ("(Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) && \"Concept templates must have parameter packs at the end.\"" , "clang/lib/Sema/SemaTemplate.cpp", 6005, __extension__ __PRETTY_FUNCTION__ )) |
| 6005 | "Concept templates must have parameter packs at the end.")(static_cast <bool> ((Template->getMostRecentDecl()-> getKind() != Decl::Kind::Concept) && "Concept templates must have parameter packs at the end." ) ? void (0) : __assert_fail ("(Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) && \"Concept templates must have parameter packs at the end.\"" , "clang/lib/Sema/SemaTemplate.cpp", 6005, __extension__ __PRETTY_FUNCTION__ )); |
| 6006 | return true; |
| 6007 | } |
| 6008 | |
| 6009 | SugaredConverted.push_back( |
| 6010 | TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); |
| 6011 | SugaredArgumentPack.clear(); |
| 6012 | |
| 6013 | CanonicalConverted.push_back( |
| 6014 | TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); |
| 6015 | CanonicalArgumentPack.clear(); |
| 6016 | |
| 6017 | ++Param; |
| 6018 | continue; |
| 6019 | } |
| 6020 | |
| 6021 | // Check whether we have a default argument. |
| 6022 | TemplateArgumentLoc Arg; |
| 6023 | |
| 6024 | // Retrieve the default template argument from the template |
| 6025 | // parameter. For each kind of template parameter, we substitute the |
| 6026 | // template arguments provided thus far and any "outer" template arguments |
| 6027 | // (when the template parameter was part of a nested template) into |
| 6028 | // the default argument. |
| 6029 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { |
| 6030 | if (!hasReachableDefaultArgument(TTP)) |
| 6031 | return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP, |
| 6032 | NewArgs); |
| 6033 | |
| 6034 | TypeSourceInfo *ArgType = SubstDefaultTemplateArgument( |
| 6035 | *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted, |
| 6036 | CanonicalConverted); |
| 6037 | if (!ArgType) |
| 6038 | return true; |
| 6039 | |
| 6040 | Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), |
| 6041 | ArgType); |
| 6042 | } else if (NonTypeTemplateParmDecl *NTTP |
| 6043 | = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { |
| 6044 | if (!hasReachableDefaultArgument(NTTP)) |
| 6045 | return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP, |
| 6046 | NewArgs); |
| 6047 | |
| 6048 | ExprResult E = SubstDefaultTemplateArgument( |
| 6049 | *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted, |
| 6050 | CanonicalConverted); |
| 6051 | if (E.isInvalid()) |
| 6052 | return true; |
| 6053 | |
| 6054 | Expr *Ex = E.getAs<Expr>(); |
| 6055 | Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); |
| 6056 | } else { |
| 6057 | TemplateTemplateParmDecl *TempParm |
| 6058 | = cast<TemplateTemplateParmDecl>(*Param); |
| 6059 | |
| 6060 | if (!hasReachableDefaultArgument(TempParm)) |
| 6061 | return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm, |
| 6062 | NewArgs); |
| 6063 | |
| 6064 | NestedNameSpecifierLoc QualifierLoc; |
| 6065 | TemplateName Name = SubstDefaultTemplateArgument( |
| 6066 | *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted, |
| 6067 | CanonicalConverted, QualifierLoc); |
| 6068 | if (Name.isNull()) |
| 6069 | return true; |
| 6070 | |
| 6071 | Arg = TemplateArgumentLoc( |
| 6072 | Context, TemplateArgument(Name), QualifierLoc, |
| 6073 | TempParm->getDefaultArgument().getTemplateNameLoc()); |
| 6074 | } |
| 6075 | |
| 6076 | // Introduce an instantiation record that describes where we are using |
| 6077 | // the default template argument. We're not actually instantiating a |
| 6078 | // template here, we just create this object to put a note into the |
| 6079 | // context stack. |
| 6080 | InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, |
| 6081 | SugaredConverted, |
| 6082 | SourceRange(TemplateLoc, RAngleLoc)); |
| 6083 | if (Inst.isInvalid()) |
| 6084 | return true; |
| 6085 | |
| 6086 | // Check the default template argument. |
| 6087 | if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0, |
| 6088 | SugaredConverted, CanonicalConverted, |
| 6089 | CTAK_Specified)) |
| 6090 | return true; |
| 6091 | |
| 6092 | CanonicalConverted.back().setIsDefaulted(true); |
| 6093 | |
| 6094 | // Core issue 150 (assumed resolution): if this is a template template |
| 6095 | // parameter, keep track of the default template arguments from the |
| 6096 | // template definition. |
| 6097 | if (isTemplateTemplateParameter) |
| 6098 | NewArgs.addArgument(Arg); |
| 6099 | |
| 6100 | // Move to the next template parameter and argument. |
| 6101 | ++Param; |
| 6102 | ++ArgIdx; |
| 6103 | } |
| 6104 | |
| 6105 | // If we're performing a partial argument substitution, allow any trailing |
| 6106 | // pack expansions; they might be empty. This can happen even if |
| 6107 | // PartialTemplateArgs is false (the list of arguments is complete but |
| 6108 | // still dependent). |
| 6109 | if (ArgIdx < NumArgs && CurrentInstantiationScope && |
| 6110 | CurrentInstantiationScope->getPartiallySubstitutedPack()) { |
| 6111 | while (ArgIdx < NumArgs && |
| 6112 | NewArgs[ArgIdx].getArgument().isPackExpansion()) { |
| 6113 | const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument(); |
| 6114 | SugaredConverted.push_back(Arg); |
| 6115 | CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg)); |
| 6116 | } |
| 6117 | } |
| 6118 | |
| 6119 | // If we have any leftover arguments, then there were too many arguments. |
| 6120 | // Complain and fail. |
| 6121 | if (ArgIdx < NumArgs) { |
| 6122 | Diag(TemplateLoc, diag::err_template_arg_list_different_arity) |
| 6123 | << /*too many args*/1 |
| 6124 | << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) |
| 6125 | << Template |
| 6126 | << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc()); |
| 6127 | Diag(Template->getLocation(), diag::note_template_decl_here) |
| 6128 | << Params->getSourceRange(); |
| 6129 | return true; |
| 6130 | } |
| 6131 | |
| 6132 | // No problems found with the new argument list, propagate changes back |
| 6133 | // to caller. |
| 6134 | if (UpdateArgsWithConversions) |
| 6135 | TemplateArgs = std::move(NewArgs); |
| 6136 | |
| 6137 | if (!PartialTemplateArgs) { |
| 6138 | TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack, |
| 6139 | CanonicalConverted); |
| 6140 | // Setup the context/ThisScope for the case where we are needing to |
| 6141 | // re-instantiate constraints outside of normal instantiation. |
| 6142 | DeclContext *NewContext = Template->getDeclContext(); |
| 6143 | |
| 6144 | // If this template is in a template, make sure we extract the templated |
| 6145 | // decl. |
| 6146 | if (auto *TD = dyn_cast<TemplateDecl>(NewContext)) |
| 6147 | NewContext = Decl::castToDeclContext(TD->getTemplatedDecl()); |
| 6148 | auto *RD = dyn_cast<CXXRecordDecl>(NewContext); |
| 6149 | |
| 6150 | Qualifiers ThisQuals; |
| 6151 | if (const auto *Method = |
| 6152 | dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl())) |
| 6153 | ThisQuals = Method->getMethodQualifiers(); |
| 6154 | |
| 6155 | ContextRAII Context(*this, NewContext); |
| 6156 | CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr); |
| 6157 | |
| 6158 | MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs( |
| 6159 | Template, /*Final=*/false, &StackTemplateArgs, |
| 6160 | /*RelativeToPrimary=*/true, |
| 6161 | /*Pattern=*/nullptr, |
| 6162 | /*ForConceptInstantiation=*/true); |
| 6163 | if (EnsureTemplateArgumentListConstraints( |
| 6164 | Template, MLTAL, |
| 6165 | SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) { |
| 6166 | if (ConstraintsNotSatisfied) |
| 6167 | *ConstraintsNotSatisfied = true; |
| 6168 | return true; |
| 6169 | } |
| 6170 | } |
| 6171 | |
| 6172 | return false; |
| 6173 | } |
| 6174 | |
| 6175 | namespace { |
| 6176 | class UnnamedLocalNoLinkageFinder |
| 6177 | : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> |
| 6178 | { |
| 6179 | Sema &S; |
| 6180 | SourceRange SR; |
| 6181 | |
| 6182 | typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; |
| 6183 | |
| 6184 | public: |
| 6185 | UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } |
| 6186 | |
| 6187 | bool Visit(QualType T) { |
| 6188 | return T.isNull() ? false : inherited::Visit(T.getTypePtr()); |
| 6189 | } |
| 6190 | |
| 6191 | #define TYPE(Class, Parent) \ |
| 6192 | bool Visit##Class##Type(const Class##Type *); |
| 6193 | #define ABSTRACT_TYPE(Class, Parent) \ |
| 6194 | bool Visit##Class##Type(const Class##Type *) { return false; } |
| 6195 | #define NON_CANONICAL_TYPE(Class, Parent) \ |
| 6196 | bool Visit##Class##Type(const Class##Type *) { return false; } |
| 6197 | #include "clang/AST/TypeNodes.inc" |
| 6198 | |
| 6199 | bool VisitTagDecl(const TagDecl *Tag); |
| 6200 | bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); |
| 6201 | }; |
| 6202 | } // end anonymous namespace |
| 6203 | |
| 6204 | bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { |
| 6205 | return false; |
| 6206 | } |
| 6207 | |
| 6208 | bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { |
| 6209 | return Visit(T->getElementType()); |
| 6210 | } |
| 6211 | |
| 6212 | bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { |
| 6213 | return Visit(T->getPointeeType()); |
| 6214 | } |
| 6215 | |
| 6216 | bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( |
| 6217 | const BlockPointerType* T) { |
| 6218 | return Visit(T->getPointeeType()); |
| 6219 | } |
| 6220 | |
| 6221 | bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( |
| 6222 | const LValueReferenceType* T) { |
| 6223 | return Visit(T->getPointeeType()); |
| 6224 | } |
| 6225 | |
| 6226 | bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( |
| 6227 | const RValueReferenceType* T) { |
| 6228 | return Visit(T->getPointeeType()); |
| 6229 | } |
| 6230 | |
| 6231 | bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( |
| 6232 | const MemberPointerType* T) { |
| 6233 | return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); |
| 6234 | } |
| 6235 | |
| 6236 | bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( |
| 6237 | const ConstantArrayType* T) { |
| 6238 | return Visit(T->getElementType()); |
| 6239 | } |
| 6240 | |
| 6241 | bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( |
| 6242 | const IncompleteArrayType* T) { |
| 6243 | return Visit(T->getElementType()); |
| 6244 | } |
| 6245 | |
| 6246 | bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( |
| 6247 | const VariableArrayType* T) { |
| 6248 | return Visit(T->getElementType()); |
| 6249 | } |
| 6250 | |
| 6251 | bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( |
| 6252 | const DependentSizedArrayType* T) { |
| 6253 | return Visit(T->getElementType()); |
| 6254 | } |
| 6255 | |
| 6256 | bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( |
| 6257 | const DependentSizedExtVectorType* T) { |
| 6258 | return Visit(T->getElementType()); |
| 6259 | } |
| 6260 | |
| 6261 | bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType( |
| 6262 | const DependentSizedMatrixType *T) { |
| 6263 | return Visit(T->getElementType()); |
| 6264 | } |
| 6265 | |
| 6266 | bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType( |
| 6267 | const DependentAddressSpaceType *T) { |
| 6268 | return Visit(T->getPointeeType()); |
| 6269 | } |
| 6270 | |
| 6271 | bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { |
| 6272 | return Visit(T->getElementType()); |
| 6273 | } |
| 6274 | |
| 6275 | bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType( |
| 6276 | const DependentVectorType *T) { |
| 6277 | return Visit(T->getElementType()); |
| 6278 | } |
| 6279 | |
| 6280 | bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { |
| 6281 | return Visit(T->getElementType()); |
| 6282 | } |
| 6283 | |
| 6284 | bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType( |
| 6285 | const ConstantMatrixType *T) { |
| 6286 | return Visit(T->getElementType()); |
| 6287 | } |
| 6288 | |
| 6289 | bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( |
| 6290 | const FunctionProtoType* T) { |
| 6291 | for (const auto &A : T->param_types()) { |
| 6292 | if (Visit(A)) |
| 6293 | return true; |
| 6294 | } |
| 6295 | |
| 6296 | return Visit(T->getReturnType()); |
| 6297 | } |
| 6298 | |
| 6299 | bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( |
| 6300 | const FunctionNoProtoType* T) { |
| 6301 | return Visit(T->getReturnType()); |
| 6302 | } |
| 6303 | |
| 6304 | bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( |
| 6305 | const UnresolvedUsingType*) { |
| 6306 | return false; |
| 6307 | } |
| 6308 | |
| 6309 | bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { |
| 6310 | return false; |
| 6311 | } |
| 6312 | |
| 6313 | bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { |
| 6314 | return Visit(T->getUnmodifiedType()); |
| 6315 | } |
| 6316 | |
| 6317 | bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { |
| 6318 | return false; |
| 6319 | } |
| 6320 | |
| 6321 | bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( |
| 6322 | const UnaryTransformType*) { |
| 6323 | return false; |
| 6324 | } |
| 6325 | |
| 6326 | bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { |
| 6327 | return Visit(T->getDeducedType()); |
| 6328 | } |
| 6329 | |
| 6330 | bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType( |
| 6331 | const DeducedTemplateSpecializationType *T) { |
| 6332 | return Visit(T->getDeducedType()); |
| 6333 | } |
| 6334 | |
| 6335 | bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { |
| 6336 | return VisitTagDecl(T->getDecl()); |
| 6337 | } |
| 6338 | |
| 6339 | bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { |
| 6340 | return VisitTagDecl(T->getDecl()); |
| 6341 | } |
| 6342 | |
| 6343 | bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( |
| 6344 | const TemplateTypeParmType*) { |
| 6345 | return false; |
| 6346 | } |
| 6347 | |
| 6348 | bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( |
| 6349 | const SubstTemplateTypeParmPackType *) { |
| 6350 | return false; |
| 6351 | } |
| 6352 | |
| 6353 | bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( |
| 6354 | const TemplateSpecializationType*) { |
| 6355 | return false; |
| 6356 | } |
| 6357 | |
| 6358 | bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( |
| 6359 | const InjectedClassNameType* T) { |
| 6360 | return VisitTagDecl(T->getDecl()); |
| 6361 | } |
| 6362 | |
| 6363 | bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( |
| 6364 | const DependentNameType* T) { |
| 6365 | return VisitNestedNameSpecifier(T->getQualifier()); |
| 6366 | } |
| 6367 | |
| 6368 | bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( |
| 6369 | const DependentTemplateSpecializationType* T) { |
| 6370 | if (auto *Q = T->getQualifier()) |
| 6371 | return VisitNestedNameSpecifier(Q); |
| 6372 | return false; |
| 6373 | } |
| 6374 | |
| 6375 | bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( |
| 6376 | const PackExpansionType* T) { |
| 6377 | return Visit(T->getPattern()); |
| 6378 | } |
| 6379 | |
| 6380 | bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { |
| 6381 | return false; |
| 6382 | } |
| 6383 | |
| 6384 | bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( |
| 6385 | const ObjCInterfaceType *) { |
| 6386 | return false; |
| 6387 | } |
| 6388 | |
| 6389 | bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( |
| 6390 | const ObjCObjectPointerType *) { |
| 6391 | return false; |
| 6392 | } |
| 6393 | |
| 6394 | bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) { |
| 6395 | return Visit(T->getValueType()); |
| 6396 | } |
| 6397 | |
| 6398 | bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) { |
| 6399 | return false; |
| 6400 | } |
| 6401 | |
| 6402 | bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) { |
| 6403 | return false; |
| 6404 | } |
| 6405 | |
| 6406 | bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType( |
| 6407 | const DependentBitIntType *T) { |
| 6408 | return false; |
| 6409 | } |
| 6410 | |
| 6411 | bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { |
| 6412 | if (Tag->getDeclContext()->isFunctionOrMethod()) { |
| 6413 | S.Diag(SR.getBegin(), |
| 6414 | S.getLangOpts().CPlusPlus11 ? |
| 6415 | diag::warn_cxx98_compat_template_arg_local_type : |
| 6416 | diag::ext_template_arg_local_type) |
| 6417 | << S.Context.getTypeDeclType(Tag) << SR; |
| 6418 | return true; |
| 6419 | } |
| 6420 | |
| 6421 | if (!Tag->hasNameForLinkage()) { |
| 6422 | S.Diag(SR.getBegin(), |
| 6423 | S.getLangOpts().CPlusPlus11 ? |
| 6424 | diag::warn_cxx98_compat_template_arg_unnamed_type : |
| 6425 | diag::ext_template_arg_unnamed_type) << SR; |
| 6426 | S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); |
| 6427 | return true; |
| 6428 | } |
| 6429 | |
| 6430 | return false; |
| 6431 | } |
| 6432 | |
| 6433 | bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( |
| 6434 | NestedNameSpecifier *NNS) { |
| 6435 | assert(NNS)(static_cast <bool> (NNS) ? void (0) : __assert_fail ("NNS" , "clang/lib/Sema/SemaTemplate.cpp", 6435, __extension__ __PRETTY_FUNCTION__ )); |
| 6436 | if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) |
| 6437 | return true; |
| 6438 | |
| 6439 | switch (NNS->getKind()) { |
| 6440 | case NestedNameSpecifier::Identifier: |
| 6441 | case NestedNameSpecifier::Namespace: |
| 6442 | case NestedNameSpecifier::NamespaceAlias: |
| 6443 | case NestedNameSpecifier::Global: |
| 6444 | case NestedNameSpecifier::Super: |
| 6445 | return false; |
| 6446 | |
| 6447 | case NestedNameSpecifier::TypeSpec: |
| 6448 | case NestedNameSpecifier::TypeSpecWithTemplate: |
| 6449 | return Visit(QualType(NNS->getAsType(), 0)); |
| 6450 | } |
| 6451 | llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!" , "clang/lib/Sema/SemaTemplate.cpp", 6451); |
| 6452 | } |
| 6453 | |
| 6454 | /// Check a template argument against its corresponding |
| 6455 | /// template type parameter. |
| 6456 | /// |
| 6457 | /// This routine implements the semantics of C++ [temp.arg.type]. It |
| 6458 | /// returns true if an error occurred, and false otherwise. |
| 6459 | bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) { |
| 6460 | assert(ArgInfo && "invalid TypeSourceInfo")(static_cast <bool> (ArgInfo && "invalid TypeSourceInfo" ) ? void (0) : __assert_fail ("ArgInfo && \"invalid TypeSourceInfo\"" , "clang/lib/Sema/SemaTemplate.cpp", 6460, __extension__ __PRETTY_FUNCTION__ )); |
| 6461 | QualType Arg = ArgInfo->getType(); |
| 6462 | SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); |
| 6463 | QualType CanonArg = Context.getCanonicalType(Arg); |
| 6464 | |
| 6465 | if (CanonArg->isVariablyModifiedType()) { |
| 6466 | return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; |
| 6467 | } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { |
| 6468 | return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; |
| 6469 | } |
| 6470 | |
| 6471 | // C++03 [temp.arg.type]p2: |
| 6472 | // A local type, a type with no linkage, an unnamed type or a type |
| 6473 | // compounded from any of these types shall not be used as a |
| 6474 | // template-argument for a template type-parameter. |
| 6475 | // |
| 6476 | // C++11 allows these, and even in C++03 we allow them as an extension with |
| 6477 | // a warning. |
| 6478 | if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) { |
| 6479 | UnnamedLocalNoLinkageFinder Finder(*this, SR); |
| 6480 | (void)Finder.Visit(CanonArg); |
| 6481 | } |
| 6482 | |
| 6483 | return false; |
| 6484 | } |
| 6485 | |
| 6486 | enum NullPointerValueKind { |
| 6487 | NPV_NotNullPointer, |
| 6488 | NPV_NullPointer, |
| 6489 | NPV_Error |
| 6490 | }; |
| 6491 | |
| 6492 | /// Determine whether the given template argument is a null pointer |
| 6493 | /// value of the appropriate type. |
| 6494 | static NullPointerValueKind |
| 6495 | isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, |
| 6496 | QualType ParamType, Expr *Arg, |
| 6497 | Decl *Entity = nullptr) { |
| 6498 | if (Arg->isValueDependent() || Arg->isTypeDependent()) |
| 6499 | return NPV_NotNullPointer; |
| 6500 | |
| 6501 | // dllimport'd entities aren't constant but are available inside of template |
| 6502 | // arguments. |
| 6503 | if (Entity && Entity->hasAttr<DLLImportAttr>()) |
| 6504 | return NPV_NotNullPointer; |
| 6505 | |
| 6506 | if (!S.isCompleteType(Arg->getExprLoc(), ParamType)) |
| 6507 | llvm_unreachable(::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!" , "clang/lib/Sema/SemaTemplate.cpp", 6508) |
| 6508 | "Incomplete parameter type in isNullPointerValueTemplateArgument!")::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!" , "clang/lib/Sema/SemaTemplate.cpp", 6508); |
| 6509 | |
| 6510 | if (!S.getLangOpts().CPlusPlus11) |
| 6511 | return NPV_NotNullPointer; |
| 6512 | |
| 6513 | // Determine whether we have a constant expression. |
| 6514 | ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg); |
| 6515 | if (ArgRV.isInvalid()) |
| 6516 | return NPV_Error; |
| 6517 | Arg = ArgRV.get(); |
| 6518 | |
| 6519 | Expr::EvalResult EvalResult; |
| 6520 | SmallVector<PartialDiagnosticAt, 8> Notes; |
| 6521 | EvalResult.Diag = &Notes; |
| 6522 | if (!Arg->EvaluateAsRValue(EvalResult, S.Context) || |
| 6523 | EvalResult.HasSideEffects) { |
| 6524 | SourceLocation DiagLoc = Arg->getExprLoc(); |
| 6525 | |
| 6526 | // If our only note is the usual "invalid subexpression" note, just point |
| 6527 | // the caret at its location rather than producing an essentially |
| 6528 | // redundant note. |
| 6529 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
| 6530 | diag::note_invalid_subexpr_in_const_expr) { |
| 6531 | DiagLoc = Notes[0].first; |
| 6532 | Notes.clear(); |
| 6533 | } |
| 6534 | |
| 6535 | S.Diag(DiagLoc, diag::err_template_arg_not_address_constant) |
| 6536 | << Arg->getType() << Arg->getSourceRange(); |
| 6537 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) |
| 6538 | S.Diag(Notes[I].first, Notes[I].second); |
| 6539 | |
| 6540 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6541 | return NPV_Error; |
| 6542 | } |
| 6543 | |
| 6544 | // C++11 [temp.arg.nontype]p1: |
| 6545 | // - an address constant expression of type std::nullptr_t |
| 6546 | if (Arg->getType()->isNullPtrType()) |
| 6547 | return NPV_NullPointer; |
| 6548 | |
| 6549 | // - a constant expression that evaluates to a null pointer value (4.10); or |
| 6550 | // - a constant expression that evaluates to a null member pointer value |
| 6551 | // (4.11); or |
| 6552 | if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) || |
| 6553 | (EvalResult.Val.isMemberPointer() && |
| 6554 | !EvalResult.Val.getMemberPointerDecl())) { |
| 6555 | // If our expression has an appropriate type, we've succeeded. |
| 6556 | bool ObjCLifetimeConversion; |
| 6557 | if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) || |
| 6558 | S.IsQualificationConversion(Arg->getType(), ParamType, false, |
| 6559 | ObjCLifetimeConversion)) |
| 6560 | return NPV_NullPointer; |
| 6561 | |
| 6562 | // The types didn't match, but we know we got a null pointer; complain, |
| 6563 | // then recover as if the types were correct. |
| 6564 | S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant) |
| 6565 | << Arg->getType() << ParamType << Arg->getSourceRange(); |
| 6566 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6567 | return NPV_NullPointer; |
| 6568 | } |
| 6569 | |
| 6570 | if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) { |
| 6571 | // We found a pointer that isn't null, but doesn't refer to an object. |
| 6572 | // We could just return NPV_NotNullPointer, but we can print a better |
| 6573 | // message with the information we have here. |
| 6574 | S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid) |
| 6575 | << EvalResult.Val.getAsString(S.Context, ParamType); |
| 6576 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6577 | return NPV_Error; |
| 6578 | } |
| 6579 | |
| 6580 | // If we don't have a null pointer value, but we do have a NULL pointer |
| 6581 | // constant, suggest a cast to the appropriate type. |
| 6582 | if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) { |
| 6583 | std::string Code = "static_cast<" + ParamType.getAsString() + ">("; |
| 6584 | S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant) |
| 6585 | << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code) |
| 6586 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()), |
| 6587 | ")"); |
| 6588 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6589 | return NPV_NullPointer; |
| 6590 | } |
| 6591 | |
| 6592 | // FIXME: If we ever want to support general, address-constant expressions |
| 6593 | // as non-type template arguments, we should return the ExprResult here to |
| 6594 | // be interpreted by the caller. |
| 6595 | return NPV_NotNullPointer; |
| 6596 | } |
| 6597 | |
| 6598 | /// Checks whether the given template argument is compatible with its |
| 6599 | /// template parameter. |
| 6600 | static bool CheckTemplateArgumentIsCompatibleWithParameter( |
| 6601 | Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, |
| 6602 | Expr *Arg, QualType ArgType) { |
| 6603 | bool ObjCLifetimeConversion; |
| 6604 | if (ParamType->isPointerType() && |
| 6605 | !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() && |
| 6606 | S.IsQualificationConversion(ArgType, ParamType, false, |
| 6607 | ObjCLifetimeConversion)) { |
| 6608 | // For pointer-to-object types, qualification conversions are |
| 6609 | // permitted. |
| 6610 | } else { |
| 6611 | if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { |
| 6612 | if (!ParamRef->getPointeeType()->isFunctionType()) { |
| 6613 | // C++ [temp.arg.nontype]p5b3: |
| 6614 | // For a non-type template-parameter of type reference to |
| 6615 | // object, no conversions apply. The type referred to by the |
| 6616 | // reference may be more cv-qualified than the (otherwise |
| 6617 | // identical) type of the template- argument. The |
| 6618 | // template-parameter is bound directly to the |
| 6619 | // template-argument, which shall be an lvalue. |
| 6620 | |
| 6621 | // FIXME: Other qualifiers? |
| 6622 | unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); |
| 6623 | unsigned ArgQuals = ArgType.getCVRQualifiers(); |
| 6624 | |
| 6625 | if ((ParamQuals | ArgQuals) != ParamQuals) { |
| 6626 | S.Diag(Arg->getBeginLoc(), |
| 6627 | diag::err_template_arg_ref_bind_ignores_quals) |
| 6628 | << ParamType << Arg->getType() << Arg->getSourceRange(); |
| 6629 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6630 | return true; |
| 6631 | } |
| 6632 | } |
| 6633 | } |
| 6634 | |
| 6635 | // At this point, the template argument refers to an object or |
| 6636 | // function with external linkage. We now need to check whether the |
| 6637 | // argument and parameter types are compatible. |
| 6638 | if (!S.Context.hasSameUnqualifiedType(ArgType, |
| 6639 | ParamType.getNonReferenceType())) { |
| 6640 | // We can't perform this conversion or binding. |
| 6641 | if (ParamType->isReferenceType()) |
| 6642 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind) |
| 6643 | << ParamType << ArgIn->getType() << Arg->getSourceRange(); |
| 6644 | else |
| 6645 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) |
| 6646 | << ArgIn->getType() << ParamType << Arg->getSourceRange(); |
| 6647 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6648 | return true; |
| 6649 | } |
| 6650 | } |
| 6651 | |
| 6652 | return false; |
| 6653 | } |
| 6654 | |
| 6655 | /// Checks whether the given template argument is the address |
| 6656 | /// of an object or function according to C++ [temp.arg.nontype]p1. |
| 6657 | static bool CheckTemplateArgumentAddressOfObjectOrFunction( |
| 6658 | Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, |
| 6659 | TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) { |
| 6660 | bool Invalid = false; |
| 6661 | Expr *Arg = ArgIn; |
| 6662 | QualType ArgType = Arg->getType(); |
| 6663 | |
| 6664 | bool AddressTaken = false; |
| 6665 | SourceLocation AddrOpLoc; |
| 6666 | if (S.getLangOpts().MicrosoftExt) { |
| 6667 | // Microsoft Visual C++ strips all casts, allows an arbitrary number of |
| 6668 | // dereference and address-of operators. |
| 6669 | Arg = Arg->IgnoreParenCasts(); |
| 6670 | |
| 6671 | bool ExtWarnMSTemplateArg = false; |
| 6672 | UnaryOperatorKind FirstOpKind; |
| 6673 | SourceLocation FirstOpLoc; |
| 6674 | while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { |
| 6675 | UnaryOperatorKind UnOpKind = UnOp->getOpcode(); |
| 6676 | if (UnOpKind == UO_Deref) |
| 6677 | ExtWarnMSTemplateArg = true; |
| 6678 | if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) { |
| 6679 | Arg = UnOp->getSubExpr()->IgnoreParenCasts(); |
| 6680 | if (!AddrOpLoc.isValid()) { |
| 6681 | FirstOpKind = UnOpKind; |
| 6682 | FirstOpLoc = UnOp->getOperatorLoc(); |
| 6683 | } |
| 6684 | } else |
| 6685 | break; |
| 6686 | } |
| 6687 | if (FirstOpLoc.isValid()) { |
| 6688 | if (ExtWarnMSTemplateArg) |
| 6689 | S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument) |
| 6690 | << ArgIn->getSourceRange(); |
| 6691 | |
| 6692 | if (FirstOpKind == UO_AddrOf) |
| 6693 | AddressTaken = true; |
| 6694 | else if (Arg->getType()->isPointerType()) { |
| 6695 | // We cannot let pointers get dereferenced here, that is obviously not a |
| 6696 | // constant expression. |
| 6697 | assert(FirstOpKind == UO_Deref)(static_cast <bool> (FirstOpKind == UO_Deref) ? void (0 ) : __assert_fail ("FirstOpKind == UO_Deref", "clang/lib/Sema/SemaTemplate.cpp" , 6697, __extension__ __PRETTY_FUNCTION__)); |
| 6698 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) |
| 6699 | << Arg->getSourceRange(); |
| 6700 | } |
| 6701 | } |
| 6702 | } else { |
| 6703 | // See through any implicit casts we added to fix the type. |
| 6704 | Arg = Arg->IgnoreImpCasts(); |
| 6705 | |
| 6706 | // C++ [temp.arg.nontype]p1: |
| 6707 | // |
| 6708 | // A template-argument for a non-type, non-template |
| 6709 | // template-parameter shall be one of: [...] |
| 6710 | // |
| 6711 | // -- the address of an object or function with external |
| 6712 | // linkage, including function templates and function |
| 6713 | // template-ids but excluding non-static class members, |
| 6714 | // expressed as & id-expression where the & is optional if |
| 6715 | // the name refers to a function or array, or if the |
| 6716 | // corresponding template-parameter is a reference; or |
| 6717 | |
| 6718 | // In C++98/03 mode, give an extension warning on any extra parentheses. |
| 6719 | // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 |
| 6720 | bool ExtraParens = false; |
| 6721 | while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { |
| 6722 | if (!Invalid && !ExtraParens) { |
| 6723 | S.Diag(Arg->getBeginLoc(), |
| 6724 | S.getLangOpts().CPlusPlus11 |
| 6725 | ? diag::warn_cxx98_compat_template_arg_extra_parens |
| 6726 | : diag::ext_template_arg_extra_parens) |
| 6727 | << Arg->getSourceRange(); |
| 6728 | ExtraParens = true; |
| 6729 | } |
| 6730 | |
| 6731 | Arg = Parens->getSubExpr(); |
| 6732 | } |
| 6733 | |
| 6734 | while (SubstNonTypeTemplateParmExpr *subst = |
| 6735 | dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) |
| 6736 | Arg = subst->getReplacement()->IgnoreImpCasts(); |
| 6737 | |
| 6738 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { |
| 6739 | if (UnOp->getOpcode() == UO_AddrOf) { |
| 6740 | Arg = UnOp->getSubExpr(); |
| 6741 | AddressTaken = true; |
| 6742 | AddrOpLoc = UnOp->getOperatorLoc(); |
| 6743 | } |
| 6744 | } |
| 6745 | |
| 6746 | while (SubstNonTypeTemplateParmExpr *subst = |
| 6747 | dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) |
| 6748 | Arg = subst->getReplacement()->IgnoreImpCasts(); |
| 6749 | } |
| 6750 | |
| 6751 | ValueDecl *Entity = nullptr; |
| 6752 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg)) |
| 6753 | Entity = DRE->getDecl(); |
| 6754 | else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg)) |
| 6755 | Entity = CUE->getGuidDecl(); |
| 6756 | |
| 6757 | // If our parameter has pointer type, check for a null template value. |
| 6758 | if (ParamType->isPointerType() || ParamType->isNullPtrType()) { |
| 6759 | switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn, |
| 6760 | Entity)) { |
| 6761 | case NPV_NullPointer: |
| 6762 | S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); |
| 6763 | SugaredConverted = TemplateArgument(ParamType, |
| 6764 | /*isNullPtr=*/true); |
| 6765 | CanonicalConverted = |
| 6766 | TemplateArgument(S.Context.getCanonicalType(ParamType), |
| 6767 | /*isNullPtr=*/true); |
| 6768 | return false; |
| 6769 | |
| 6770 | case NPV_Error: |
| 6771 | return true; |
| 6772 | |
| 6773 | case NPV_NotNullPointer: |
| 6774 | break; |
| 6775 | } |
| 6776 | } |
| 6777 | |
| 6778 | // Stop checking the precise nature of the argument if it is value dependent, |
| 6779 | // it should be checked when instantiated. |
| 6780 | if (Arg->isValueDependent()) { |
| 6781 | SugaredConverted = TemplateArgument(ArgIn); |
| 6782 | CanonicalConverted = |
| 6783 | S.Context.getCanonicalTemplateArgument(SugaredConverted); |
| 6784 | return false; |
| 6785 | } |
| 6786 | |
| 6787 | if (!Entity) { |
| 6788 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) |
| 6789 | << Arg->getSourceRange(); |
| 6790 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6791 | return true; |
| 6792 | } |
| 6793 | |
| 6794 | // Cannot refer to non-static data members |
| 6795 | if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) { |
| 6796 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field) |
| 6797 | << Entity << Arg->getSourceRange(); |
| 6798 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6799 | return true; |
| 6800 | } |
| 6801 | |
| 6802 | // Cannot refer to non-static member functions |
| 6803 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) { |
| 6804 | if (!Method->isStatic()) { |
| 6805 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method) |
| 6806 | << Method << Arg->getSourceRange(); |
| 6807 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6808 | return true; |
| 6809 | } |
| 6810 | } |
| 6811 | |
| 6812 | FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity); |
| 6813 | VarDecl *Var = dyn_cast<VarDecl>(Entity); |
| 6814 | MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity); |
| 6815 | |
| 6816 | // A non-type template argument must refer to an object or function. |
| 6817 | if (!Func && !Var && !Guid) { |
| 6818 | // We found something, but we don't know specifically what it is. |
| 6819 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func) |
| 6820 | << Arg->getSourceRange(); |
| 6821 | S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here); |
| 6822 | return true; |
| 6823 | } |
| 6824 | |
| 6825 | // Address / reference template args must have external linkage in C++98. |
| 6826 | if (Entity->getFormalLinkage() == InternalLinkage) { |
| 6827 | S.Diag(Arg->getBeginLoc(), |
| 6828 | S.getLangOpts().CPlusPlus11 |
| 6829 | ? diag::warn_cxx98_compat_template_arg_object_internal |
| 6830 | : diag::ext_template_arg_object_internal) |
| 6831 | << !Func << Entity << Arg->getSourceRange(); |
| 6832 | S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) |
| 6833 | << !Func; |
| 6834 | } else if (!Entity->hasLinkage()) { |
| 6835 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage) |
| 6836 | << !Func << Entity << Arg->getSourceRange(); |
| 6837 | S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) |
| 6838 | << !Func; |
| 6839 | return true; |
| 6840 | } |
| 6841 | |
| 6842 | if (Var) { |
| 6843 | // A value of reference type is not an object. |
| 6844 | if (Var->getType()->isReferenceType()) { |
| 6845 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var) |
| 6846 | << Var->getType() << Arg->getSourceRange(); |
| 6847 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6848 | return true; |
| 6849 | } |
| 6850 | |
| 6851 | // A template argument must have static storage duration. |
| 6852 | if (Var->getTLSKind()) { |
| 6853 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local) |
| 6854 | << Arg->getSourceRange(); |
| 6855 | S.Diag(Var->getLocation(), diag::note_template_arg_refers_here); |
| 6856 | return true; |
| 6857 | } |
| 6858 | } |
| 6859 | |
| 6860 | if (AddressTaken && ParamType->isReferenceType()) { |
| 6861 | // If we originally had an address-of operator, but the |
| 6862 | // parameter has reference type, complain and (if things look |
| 6863 | // like they will work) drop the address-of operator. |
| 6864 | if (!S.Context.hasSameUnqualifiedType(Entity->getType(), |
| 6865 | ParamType.getNonReferenceType())) { |
| 6866 | S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) |
| 6867 | << ParamType; |
| 6868 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6869 | return true; |
| 6870 | } |
| 6871 | |
| 6872 | S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) |
| 6873 | << ParamType |
| 6874 | << FixItHint::CreateRemoval(AddrOpLoc); |
| 6875 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6876 | |
| 6877 | ArgType = Entity->getType(); |
| 6878 | } |
| 6879 | |
| 6880 | // If the template parameter has pointer type, either we must have taken the |
| 6881 | // address or the argument must decay to a pointer. |
| 6882 | if (!AddressTaken && ParamType->isPointerType()) { |
| 6883 | if (Func) { |
| 6884 | // Function-to-pointer decay. |
| 6885 | ArgType = S.Context.getPointerType(Func->getType()); |
| 6886 | } else if (Entity->getType()->isArrayType()) { |
| 6887 | // Array-to-pointer decay. |
| 6888 | ArgType = S.Context.getArrayDecayedType(Entity->getType()); |
| 6889 | } else { |
| 6890 | // If the template parameter has pointer type but the address of |
| 6891 | // this object was not taken, complain and (possibly) recover by |
| 6892 | // taking the address of the entity. |
| 6893 | ArgType = S.Context.getPointerType(Entity->getType()); |
| 6894 | if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { |
| 6895 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) |
| 6896 | << ParamType; |
| 6897 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6898 | return true; |
| 6899 | } |
| 6900 | |
| 6901 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) |
| 6902 | << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&"); |
| 6903 | |
| 6904 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 6905 | } |
| 6906 | } |
| 6907 | |
| 6908 | if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn, |
| 6909 | Arg, ArgType)) |
| 6910 | return true; |
| 6911 | |
| 6912 | // Create the template argument. |
| 6913 | SugaredConverted = TemplateArgument(Entity, ParamType); |
| 6914 | CanonicalConverted = |
| 6915 | TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), |
| 6916 | S.Context.getCanonicalType(ParamType)); |
| 6917 | S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false); |
| 6918 | return false; |
| 6919 | } |
| 6920 | |
| 6921 | /// Checks whether the given template argument is a pointer to |
| 6922 | /// member constant according to C++ [temp.arg.nontype]p1. |
| 6923 | static bool |
| 6924 | CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, |
| 6925 | QualType ParamType, Expr *&ResultArg, |
| 6926 | TemplateArgument &SugaredConverted, |
| 6927 | TemplateArgument &CanonicalConverted) { |
| 6928 | bool Invalid = false; |
| 6929 | |
| 6930 | Expr *Arg = ResultArg; |
| 6931 | bool ObjCLifetimeConversion; |
| 6932 | |
| 6933 | // C++ [temp.arg.nontype]p1: |
| 6934 | // |
| 6935 | // A template-argument for a non-type, non-template |
| 6936 | // template-parameter shall be one of: [...] |
| 6937 | // |
| 6938 | // -- a pointer to member expressed as described in 5.3.1. |
| 6939 | DeclRefExpr *DRE = nullptr; |
| 6940 | |
| 6941 | // In C++98/03 mode, give an extension warning on any extra parentheses. |
| 6942 | // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 |
| 6943 | bool ExtraParens = false; |
| 6944 | while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { |
| 6945 | if (!Invalid && !ExtraParens) { |
| 6946 | S.Diag(Arg->getBeginLoc(), |
| 6947 | S.getLangOpts().CPlusPlus11 |
| 6948 | ? diag::warn_cxx98_compat_template_arg_extra_parens |
| 6949 | : diag::ext_template_arg_extra_parens) |
| 6950 | << Arg->getSourceRange(); |
| 6951 | ExtraParens = true; |
| 6952 | } |
| 6953 | |
| 6954 | Arg = Parens->getSubExpr(); |
| 6955 | } |
| 6956 | |
| 6957 | while (SubstNonTypeTemplateParmExpr *subst = |
| 6958 | dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) |
| 6959 | Arg = subst->getReplacement()->IgnoreImpCasts(); |
| 6960 | |
| 6961 | // A pointer-to-member constant written &Class::member. |
| 6962 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { |
| 6963 | if (UnOp->getOpcode() == UO_AddrOf) { |
| 6964 | DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); |
| 6965 | if (DRE && !DRE->getQualifier()) |
| 6966 | DRE = nullptr; |
| 6967 | } |
| 6968 | } |
| 6969 | // A constant of pointer-to-member type. |
| 6970 | else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { |
| 6971 | ValueDecl *VD = DRE->getDecl(); |
| 6972 | if (VD->getType()->isMemberPointerType()) { |
| 6973 | if (isa<NonTypeTemplateParmDecl>(VD)) { |
| 6974 | if (Arg->isTypeDependent() || Arg->isValueDependent()) { |
| 6975 | SugaredConverted = TemplateArgument(Arg); |
| 6976 | CanonicalConverted = |
| 6977 | S.Context.getCanonicalTemplateArgument(SugaredConverted); |
| 6978 | } else { |
| 6979 | SugaredConverted = TemplateArgument(VD, ParamType); |
| 6980 | CanonicalConverted = |
| 6981 | TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), |
| 6982 | S.Context.getCanonicalType(ParamType)); |
| 6983 | } |
| 6984 | return Invalid; |
| 6985 | } |
| 6986 | } |
| 6987 | |
| 6988 | DRE = nullptr; |
| 6989 | } |
| 6990 | |
| 6991 | ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr; |
| 6992 | |
| 6993 | // Check for a null pointer value. |
| 6994 | switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg, |
| 6995 | Entity)) { |
| 6996 | case NPV_Error: |
| 6997 | return true; |
| 6998 | case NPV_NullPointer: |
| 6999 | S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); |
| 7000 | SugaredConverted = TemplateArgument(ParamType, |
| 7001 | /*isNullPtr*/ true); |
| 7002 | CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType), |
| 7003 | /*isNullPtr*/ true); |
| 7004 | return false; |
| 7005 | case NPV_NotNullPointer: |
| 7006 | break; |
| 7007 | } |
| 7008 | |
| 7009 | if (S.IsQualificationConversion(ResultArg->getType(), |
| 7010 | ParamType.getNonReferenceType(), false, |
| 7011 | ObjCLifetimeConversion)) { |
| 7012 | ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp, |
| 7013 | ResultArg->getValueKind()) |
| 7014 | .get(); |
| 7015 | } else if (!S.Context.hasSameUnqualifiedType( |
| 7016 | ResultArg->getType(), ParamType.getNonReferenceType())) { |
| 7017 | // We can't perform this conversion. |
| 7018 | S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible) |
| 7019 | << ResultArg->getType() << ParamType << ResultArg->getSourceRange(); |
| 7020 | S.Diag(Param->getLocation(), diag::note_template_param_here); |
| 7021 | return true; |
| 7022 | } |
| 7023 | |
| 7024 | if (!DRE) |
| 7025 | return S.Diag(Arg->getBeginLoc(), |
| 7026 | diag::err_template_arg_not_pointer_to_member_form) |
| 7027 | << Arg->getSourceRange(); |
| 7028 | |
| 7029 | if (isa<FieldDecl>(DRE->getDecl()) || |
| 7030 | isa<IndirectFieldDecl>(DRE->getDecl()) || |
| 7031 | isa<CXXMethodDecl>(DRE->getDecl())) { |
| 7032 | assert((isa<FieldDecl>(DRE->getDecl()) ||(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl ()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast <CXXMethodDecl>(DRE->getDecl())->isStatic()) && "Only non-static member pointers can make it here") ? void ( 0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7035, __extension__ __PRETTY_FUNCTION__ )) |
| 7033 | isa<IndirectFieldDecl>(DRE->getDecl()) ||(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl ()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast <CXXMethodDecl>(DRE->getDecl())->isStatic()) && "Only non-static member pointers can make it here") ? void ( 0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7035, __extension__ __PRETTY_FUNCTION__ )) |
| 7034 | !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl ()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast <CXXMethodDecl>(DRE->getDecl())->isStatic()) && "Only non-static member pointers can make it here") ? void ( 0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7035, __extension__ __PRETTY_FUNCTION__ )) |
| 7035 | "Only non-static member pointers can make it here")(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl ()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast <CXXMethodDecl>(DRE->getDecl())->isStatic()) && "Only non-static member pointers can make it here") ? void ( 0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7035, __extension__ __PRETTY_FUNCTION__ )); |
| 7036 | |
| 7037 | // Okay: this is the address of a non-static member, and therefore |
| 7038 | // a member pointer constant. |
| 7039 | if (Arg->isTypeDependent() || Arg->isValueDependent()) { |
| 7040 | SugaredConverted = TemplateArgument(Arg); |
| 7041 | CanonicalConverted = |
| 7042 | S.Context.getCanonicalTemplateArgument(SugaredConverted); |
| 7043 | } else { |
| 7044 | ValueDecl *D = DRE->getDecl(); |
| 7045 | SugaredConverted = TemplateArgument(D, ParamType); |
| 7046 | CanonicalConverted = |
| 7047 | TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()), |
| 7048 | S.Context.getCanonicalType(ParamType)); |
| 7049 | } |
| 7050 | return Invalid; |
| 7051 | } |
| 7052 | |
| 7053 | // We found something else, but we don't know specifically what it is. |
| 7054 | S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form) |
| 7055 | << Arg->getSourceRange(); |
| 7056 | S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); |
| 7057 | return true; |
| 7058 | } |
| 7059 | |
| 7060 | /// Check a template argument against its corresponding |
| 7061 | /// non-type template parameter. |
| 7062 | /// |
| 7063 | /// This routine implements the semantics of C++ [temp.arg.nontype]. |
| 7064 | /// If an error occurred, it returns ExprError(); otherwise, it |
| 7065 | /// returns the converted template argument. \p ParamType is the |
| 7066 | /// type of the non-type template parameter after it has been instantiated. |
| 7067 | ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, |
| 7068 | QualType ParamType, Expr *Arg, |
| 7069 | TemplateArgument &SugaredConverted, |
| 7070 | TemplateArgument &CanonicalConverted, |
| 7071 | CheckTemplateArgumentKind CTAK) { |
| 7072 | SourceLocation StartLoc = Arg->getBeginLoc(); |
| 7073 | |
| 7074 | // If the parameter type somehow involves auto, deduce the type now. |
| 7075 | DeducedType *DeducedT = ParamType->getContainedDeducedType(); |
| 7076 | if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) { |
| 7077 | // During template argument deduction, we allow 'decltype(auto)' to |
| 7078 | // match an arbitrary dependent argument. |
| 7079 | // FIXME: The language rules don't say what happens in this case. |
| 7080 | // FIXME: We get an opaque dependent type out of decltype(auto) if the |
| 7081 | // expression is merely instantiation-dependent; is this enough? |
| 7082 | if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) { |
| 7083 | auto *AT = dyn_cast<AutoType>(DeducedT); |
| 7084 | if (AT && AT->isDecltypeAuto()) { |
| 7085 | SugaredConverted = TemplateArgument(Arg); |
| 7086 | CanonicalConverted = TemplateArgument( |
| 7087 | Context.getCanonicalTemplateArgument(SugaredConverted)); |
| 7088 | return Arg; |
| 7089 | } |
| 7090 | } |
| 7091 | |
| 7092 | // When checking a deduced template argument, deduce from its type even if |
| 7093 | // the type is dependent, in order to check the types of non-type template |
| 7094 | // arguments line up properly in partial ordering. |
| 7095 | Expr *DeductionArg = Arg; |
| 7096 | if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg)) |
| 7097 | DeductionArg = PE->getPattern(); |
| 7098 | TypeSourceInfo *TSI = |
| 7099 | Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()); |
| 7100 | if (isa<DeducedTemplateSpecializationType>(DeducedT)) { |
| 7101 | InitializedEntity Entity = |
| 7102 | InitializedEntity::InitializeTemplateParameter(ParamType, Param); |
| 7103 | InitializationKind Kind = InitializationKind::CreateForInit( |
| 7104 | DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg); |
| 7105 | Expr *Inits[1] = {DeductionArg}; |
| 7106 | ParamType = |
| 7107 | DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits); |
| 7108 | if (ParamType.isNull()) |
| 7109 | return ExprError(); |
| 7110 | } else { |
| 7111 | TemplateDeductionInfo Info(DeductionArg->getExprLoc(), |
| 7112 | Param->getDepth() + 1); |
| 7113 | ParamType = QualType(); |
| 7114 | TemplateDeductionResult Result = |
| 7115 | DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info, |
| 7116 | /*DependentDeduction=*/true, |
| 7117 | // We do not check constraints right now because the |
| 7118 | // immediately-declared constraint of the auto type is |
| 7119 | // also an associated constraint, and will be checked |
| 7120 | // along with the other associated constraints after |
| 7121 | // checking the template argument list. |
| 7122 | /*IgnoreConstraints=*/true); |
| 7123 | if (Result == TDK_AlreadyDiagnosed) { |
| 7124 | if (ParamType.isNull()) |
| 7125 | return ExprError(); |
| 7126 | } else if (Result != TDK_Success) { |
| 7127 | Diag(Arg->getExprLoc(), |
| 7128 | diag::err_non_type_template_parm_type_deduction_failure) |
| 7129 | << Param->getDeclName() << Param->getType() << Arg->getType() |
| 7130 | << Arg->getSourceRange(); |
| 7131 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7132 | return ExprError(); |
| 7133 | } |
| 7134 | } |
| 7135 | // CheckNonTypeTemplateParameterType will produce a diagnostic if there's |
| 7136 | // an error. The error message normally references the parameter |
| 7137 | // declaration, but here we'll pass the argument location because that's |
| 7138 | // where the parameter type is deduced. |
| 7139 | ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc()); |
| 7140 | if (ParamType.isNull()) { |
| 7141 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7142 | return ExprError(); |
| 7143 | } |
| 7144 | } |
| 7145 | |
| 7146 | // We should have already dropped all cv-qualifiers by now. |
| 7147 | assert(!ParamType.hasQualifiers() &&(static_cast <bool> (!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified") ? void (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\"" , "clang/lib/Sema/SemaTemplate.cpp", 7148, __extension__ __PRETTY_FUNCTION__ )) |
| 7148 | "non-type template parameter type cannot be qualified")(static_cast <bool> (!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified") ? void (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\"" , "clang/lib/Sema/SemaTemplate.cpp", 7148, __extension__ __PRETTY_FUNCTION__ )); |
| 7149 | |
| 7150 | // FIXME: When Param is a reference, should we check that Arg is an lvalue? |
| 7151 | if (CTAK == CTAK_Deduced && |
| 7152 | (ParamType->isReferenceType() |
| 7153 | ? !Context.hasSameType(ParamType.getNonReferenceType(), |
| 7154 | Arg->getType()) |
| 7155 | : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) { |
| 7156 | // FIXME: If either type is dependent, we skip the check. This isn't |
| 7157 | // correct, since during deduction we're supposed to have replaced each |
| 7158 | // template parameter with some unique (non-dependent) placeholder. |
| 7159 | // FIXME: If the argument type contains 'auto', we carry on and fail the |
| 7160 | // type check in order to force specific types to be more specialized than |
| 7161 | // 'auto'. It's not clear how partial ordering with 'auto' is supposed to |
| 7162 | // work. Similarly for CTAD, when comparing 'A<x>' against 'A'. |
| 7163 | if ((ParamType->isDependentType() || Arg->isTypeDependent()) && |
| 7164 | !Arg->getType()->getContainedDeducedType()) { |
| 7165 | SugaredConverted = TemplateArgument(Arg); |
| 7166 | CanonicalConverted = TemplateArgument( |
| 7167 | Context.getCanonicalTemplateArgument(SugaredConverted)); |
| 7168 | return Arg; |
| 7169 | } |
| 7170 | // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770, |
| 7171 | // we should actually be checking the type of the template argument in P, |
| 7172 | // not the type of the template argument deduced from A, against the |
| 7173 | // template parameter type. |
| 7174 | Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) |
| 7175 | << Arg->getType() |
| 7176 | << ParamType.getUnqualifiedType(); |
| 7177 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7178 | return ExprError(); |
| 7179 | } |
| 7180 | |
| 7181 | // If either the parameter has a dependent type or the argument is |
| 7182 | // type-dependent, there's nothing we can check now. |
| 7183 | if (ParamType->isDependentType() || Arg->isTypeDependent()) { |
| 7184 | // Force the argument to the type of the parameter to maintain invariants. |
| 7185 | auto *PE = dyn_cast<PackExpansionExpr>(Arg); |
| 7186 | if (PE) |
| 7187 | Arg = PE->getPattern(); |
| 7188 | ExprResult E = ImpCastExprToType( |
| 7189 | Arg, ParamType.getNonLValueExprType(Context), CK_Dependent, |
| 7190 | ParamType->isLValueReferenceType() ? VK_LValue |
| 7191 | : ParamType->isRValueReferenceType() ? VK_XValue |
| 7192 | : VK_PRValue); |
| 7193 | if (E.isInvalid()) |
| 7194 | return ExprError(); |
| 7195 | if (PE) { |
| 7196 | // Recreate a pack expansion if we unwrapped one. |
| 7197 | E = new (Context) |
| 7198 | PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(), |
| 7199 | PE->getNumExpansions()); |
| 7200 | } |
| 7201 | SugaredConverted = TemplateArgument(E.get()); |
| 7202 | CanonicalConverted = TemplateArgument( |
| 7203 | Context.getCanonicalTemplateArgument(SugaredConverted)); |
| 7204 | return E; |
| 7205 | } |
| 7206 | |
| 7207 | // The initialization of the parameter from the argument is |
| 7208 | // a constant-evaluated context. |
| 7209 | EnterExpressionEvaluationContext ConstantEvaluated( |
| 7210 | *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
| 7211 | |
| 7212 | if (getLangOpts().CPlusPlus17) { |
| 7213 | QualType CanonParamType = Context.getCanonicalType(ParamType); |
| 7214 | |
| 7215 | // Avoid making a copy when initializing a template parameter of class type |
| 7216 | // from a template parameter object of the same type. This is going beyond |
| 7217 | // the standard, but is required for soundness: in |
| 7218 | // template<A a> struct X { X *p; X<a> *q; }; |
| 7219 | // ... we need p and q to have the same type. |
| 7220 | // |
| 7221 | // Similarly, don't inject a call to a copy constructor when initializing |
| 7222 | // from a template parameter of the same type. |
| 7223 | Expr *InnerArg = Arg->IgnoreParenImpCasts(); |
| 7224 | if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) && |
| 7225 | Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) { |
| 7226 | NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl(); |
| 7227 | if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { |
| 7228 | |
| 7229 | SugaredConverted = TemplateArgument(TPO, ParamType); |
| 7230 | CanonicalConverted = |
| 7231 | TemplateArgument(TPO->getCanonicalDecl(), CanonParamType); |
| 7232 | return Arg; |
| 7233 | } |
| 7234 | if (isa<NonTypeTemplateParmDecl>(ND)) { |
| 7235 | SugaredConverted = TemplateArgument(Arg); |
| 7236 | CanonicalConverted = |
| 7237 | Context.getCanonicalTemplateArgument(SugaredConverted); |
| 7238 | return Arg; |
| 7239 | } |
| 7240 | } |
| 7241 | |
| 7242 | // C++17 [temp.arg.nontype]p1: |
| 7243 | // A template-argument for a non-type template parameter shall be |
| 7244 | // a converted constant expression of the type of the template-parameter. |
| 7245 | APValue Value; |
| 7246 | ExprResult ArgResult = CheckConvertedConstantExpression( |
| 7247 | Arg, ParamType, Value, CCEK_TemplateArg, Param); |
| 7248 | if (ArgResult.isInvalid()) |
| 7249 | return ExprError(); |
| 7250 | |
| 7251 | // For a value-dependent argument, CheckConvertedConstantExpression is |
| 7252 | // permitted (and expected) to be unable to determine a value. |
| 7253 | if (ArgResult.get()->isValueDependent()) { |
| 7254 | SugaredConverted = TemplateArgument(ArgResult.get()); |
| 7255 | CanonicalConverted = |
| 7256 | Context.getCanonicalTemplateArgument(SugaredConverted); |
| 7257 | return ArgResult; |
| 7258 | } |
| 7259 | |
| 7260 | // Convert the APValue to a TemplateArgument. |
| 7261 | switch (Value.getKind()) { |
| 7262 | case APValue::None: |
| 7263 | assert(ParamType->isNullPtrType())(static_cast <bool> (ParamType->isNullPtrType()) ? void (0) : __assert_fail ("ParamType->isNullPtrType()", "clang/lib/Sema/SemaTemplate.cpp" , 7263, __extension__ __PRETTY_FUNCTION__)); |
| 7264 | SugaredConverted = TemplateArgument(ParamType, /*isNullPtr=*/true); |
| 7265 | CanonicalConverted = TemplateArgument(CanonParamType, /*isNullPtr=*/true); |
| 7266 | break; |
| 7267 | case APValue::Indeterminate: |
| 7268 | llvm_unreachable("result of constant evaluation should be initialized")::llvm::llvm_unreachable_internal("result of constant evaluation should be initialized" , "clang/lib/Sema/SemaTemplate.cpp", 7268); |
| 7269 | break; |
| 7270 | case APValue::Int: |
| 7271 | assert(ParamType->isIntegralOrEnumerationType())(static_cast <bool> (ParamType->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("ParamType->isIntegralOrEnumerationType()" , "clang/lib/Sema/SemaTemplate.cpp", 7271, __extension__ __PRETTY_FUNCTION__ )); |
| 7272 | SugaredConverted = TemplateArgument(Context, Value.getInt(), ParamType); |
| 7273 | CanonicalConverted = |
| 7274 | TemplateArgument(Context, Value.getInt(), CanonParamType); |
| 7275 | break; |
| 7276 | case APValue::MemberPointer: { |
| 7277 | assert(ParamType->isMemberPointerType())(static_cast <bool> (ParamType->isMemberPointerType( )) ? void (0) : __assert_fail ("ParamType->isMemberPointerType()" , "clang/lib/Sema/SemaTemplate.cpp", 7277, __extension__ __PRETTY_FUNCTION__ )); |
| 7278 | |
| 7279 | // FIXME: We need TemplateArgument representation and mangling for these. |
| 7280 | if (!Value.getMemberPointerPath().empty()) { |
| 7281 | Diag(Arg->getBeginLoc(), |
| 7282 | diag::err_template_arg_member_ptr_base_derived_not_supported) |
| 7283 | << Value.getMemberPointerDecl() << ParamType |
| 7284 | << Arg->getSourceRange(); |
| 7285 | return ExprError(); |
| 7286 | } |
| 7287 | |
| 7288 | auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl()); |
| 7289 | SugaredConverted = VD ? TemplateArgument(VD, ParamType) |
| 7290 | : TemplateArgument(ParamType, /*isNullPtr=*/true); |
| 7291 | CanonicalConverted = |
| 7292 | VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), |
| 7293 | CanonParamType) |
| 7294 | : TemplateArgument(CanonParamType, /*isNullPtr=*/true); |
| 7295 | break; |
| 7296 | } |
| 7297 | case APValue::LValue: { |
| 7298 | // For a non-type template-parameter of pointer or reference type, |
| 7299 | // the value of the constant expression shall not refer to |
| 7300 | assert(ParamType->isPointerType() || ParamType->isReferenceType() ||(static_cast <bool> (ParamType->isPointerType() || ParamType ->isReferenceType() || ParamType->isNullPtrType()) ? void (0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()" , "clang/lib/Sema/SemaTemplate.cpp", 7301, __extension__ __PRETTY_FUNCTION__ )) |
| 7301 | ParamType->isNullPtrType())(static_cast <bool> (ParamType->isPointerType() || ParamType ->isReferenceType() || ParamType->isNullPtrType()) ? void (0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()" , "clang/lib/Sema/SemaTemplate.cpp", 7301, __extension__ __PRETTY_FUNCTION__ )); |
| 7302 | // -- a temporary object |
| 7303 | // -- a string literal |
| 7304 | // -- the result of a typeid expression, or |
| 7305 | // -- a predefined __func__ variable |
| 7306 | APValue::LValueBase Base = Value.getLValueBase(); |
| 7307 | auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>()); |
| 7308 | if (Base && |
| 7309 | (!VD || |
| 7310 | isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) { |
| 7311 | Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) |
| 7312 | << Arg->getSourceRange(); |
| 7313 | return ExprError(); |
| 7314 | } |
| 7315 | // -- a subobject |
| 7316 | // FIXME: Until C++20 |
| 7317 | if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && |
| 7318 | VD && VD->getType()->isArrayType() && |
| 7319 | Value.getLValuePath()[0].getAsArrayIndex() == 0 && |
| 7320 | !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) { |
| 7321 | // Per defect report (no number yet): |
| 7322 | // ... other than a pointer to the first element of a complete array |
| 7323 | // object. |
| 7324 | } else if (!Value.hasLValuePath() || Value.getLValuePath().size() || |
| 7325 | Value.isLValueOnePastTheEnd()) { |
| 7326 | Diag(StartLoc, diag::err_non_type_template_arg_subobject) |
| 7327 | << Value.getAsString(Context, ParamType); |
| 7328 | return ExprError(); |
| 7329 | } |
| 7330 | assert((VD || !ParamType->isReferenceType()) &&(static_cast <bool> ((VD || !ParamType->isReferenceType ()) && "null reference should not be a constant expression" ) ? void (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\"" , "clang/lib/Sema/SemaTemplate.cpp", 7331, __extension__ __PRETTY_FUNCTION__ )) |
| 7331 | "null reference should not be a constant expression")(static_cast <bool> ((VD || !ParamType->isReferenceType ()) && "null reference should not be a constant expression" ) ? void (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\"" , "clang/lib/Sema/SemaTemplate.cpp", 7331, __extension__ __PRETTY_FUNCTION__ )); |
| 7332 | assert((!VD || !ParamType->isNullPtrType()) &&(static_cast <bool> ((!VD || !ParamType->isNullPtrType ()) && "non-null value of type nullptr_t?") ? void (0 ) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\"" , "clang/lib/Sema/SemaTemplate.cpp", 7333, __extension__ __PRETTY_FUNCTION__ )) |
| 7333 | "non-null value of type nullptr_t?")(static_cast <bool> ((!VD || !ParamType->isNullPtrType ()) && "non-null value of type nullptr_t?") ? void (0 ) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\"" , "clang/lib/Sema/SemaTemplate.cpp", 7333, __extension__ __PRETTY_FUNCTION__ )); |
| 7334 | |
| 7335 | SugaredConverted = VD ? TemplateArgument(VD, ParamType) |
| 7336 | : TemplateArgument(ParamType, /*isNullPtr=*/true); |
| 7337 | CanonicalConverted = |
| 7338 | VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), |
| 7339 | CanonParamType) |
| 7340 | : TemplateArgument(CanonParamType, /*isNullPtr=*/true); |
| 7341 | break; |
| 7342 | } |
| 7343 | case APValue::Struct: |
| 7344 | case APValue::Union: { |
| 7345 | // Get or create the corresponding template parameter object. |
| 7346 | TemplateParamObjectDecl *D = |
| 7347 | Context.getTemplateParamObjectDecl(ParamType, Value); |
| 7348 | SugaredConverted = TemplateArgument(D, ParamType); |
| 7349 | CanonicalConverted = |
| 7350 | TemplateArgument(D->getCanonicalDecl(), CanonParamType); |
| 7351 | break; |
| 7352 | } |
| 7353 | case APValue::AddrLabelDiff: |
| 7354 | return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff); |
| 7355 | case APValue::FixedPoint: |
| 7356 | case APValue::Float: |
| 7357 | case APValue::ComplexInt: |
| 7358 | case APValue::ComplexFloat: |
| 7359 | case APValue::Vector: |
| 7360 | case APValue::Array: |
| 7361 | return Diag(StartLoc, diag::err_non_type_template_arg_unsupported) |
| 7362 | << ParamType; |
| 7363 | } |
| 7364 | |
| 7365 | return ArgResult.get(); |
| 7366 | } |
| 7367 | |
| 7368 | // C++ [temp.arg.nontype]p5: |
| 7369 | // The following conversions are performed on each expression used |
| 7370 | // as a non-type template-argument. If a non-type |
| 7371 | // template-argument cannot be converted to the type of the |
| 7372 | // corresponding template-parameter then the program is |
| 7373 | // ill-formed. |
| 7374 | if (ParamType->isIntegralOrEnumerationType()) { |
| 7375 | // C++11: |
| 7376 | // -- for a non-type template-parameter of integral or |
| 7377 | // enumeration type, conversions permitted in a converted |
| 7378 | // constant expression are applied. |
| 7379 | // |
| 7380 | // C++98: |
| 7381 | // -- for a non-type template-parameter of integral or |
| 7382 | // enumeration type, integral promotions (4.5) and integral |
| 7383 | // conversions (4.7) are applied. |
| 7384 | |
| 7385 | if (getLangOpts().CPlusPlus11) { |
| 7386 | // C++ [temp.arg.nontype]p1: |
| 7387 | // A template-argument for a non-type, non-template template-parameter |
| 7388 | // shall be one of: |
| 7389 | // |
| 7390 | // -- for a non-type template-parameter of integral or enumeration |
| 7391 | // type, a converted constant expression of the type of the |
| 7392 | // template-parameter; or |
| 7393 | llvm::APSInt Value; |
| 7394 | ExprResult ArgResult = |
| 7395 | CheckConvertedConstantExpression(Arg, ParamType, Value, |
| 7396 | CCEK_TemplateArg); |
| 7397 | if (ArgResult.isInvalid()) |
| 7398 | return ExprError(); |
| 7399 | |
| 7400 | // We can't check arbitrary value-dependent arguments. |
| 7401 | if (ArgResult.get()->isValueDependent()) { |
| 7402 | SugaredConverted = TemplateArgument(ArgResult.get()); |
| 7403 | CanonicalConverted = |
| 7404 | Context.getCanonicalTemplateArgument(SugaredConverted); |
| 7405 | return ArgResult; |
| 7406 | } |
| 7407 | |
| 7408 | // Widen the argument value to sizeof(parameter type). This is almost |
| 7409 | // always a no-op, except when the parameter type is bool. In |
| 7410 | // that case, this may extend the argument from 1 bit to 8 bits. |
| 7411 | QualType IntegerType = ParamType; |
| 7412 | if (const EnumType *Enum = IntegerType->getAs<EnumType>()) |
| 7413 | IntegerType = Enum->getDecl()->getIntegerType(); |
| 7414 | Value = Value.extOrTrunc(IntegerType->isBitIntType() |
| 7415 | ? Context.getIntWidth(IntegerType) |
| 7416 | : Context.getTypeSize(IntegerType)); |
| 7417 | |
| 7418 | SugaredConverted = TemplateArgument(Context, Value, ParamType); |
| 7419 | CanonicalConverted = |
| 7420 | TemplateArgument(Context, Value, Context.getCanonicalType(ParamType)); |
| 7421 | return ArgResult; |
| 7422 | } |
| 7423 | |
| 7424 | ExprResult ArgResult = DefaultLvalueConversion(Arg); |
| 7425 | if (ArgResult.isInvalid()) |
| 7426 | return ExprError(); |
| 7427 | Arg = ArgResult.get(); |
| 7428 | |
| 7429 | QualType ArgType = Arg->getType(); |
| 7430 | |
| 7431 | // C++ [temp.arg.nontype]p1: |
| 7432 | // A template-argument for a non-type, non-template |
| 7433 | // template-parameter shall be one of: |
| 7434 | // |
| 7435 | // -- an integral constant-expression of integral or enumeration |
| 7436 | // type; or |
| 7437 | // -- the name of a non-type template-parameter; or |
| 7438 | llvm::APSInt Value; |
| 7439 | if (!ArgType->isIntegralOrEnumerationType()) { |
| 7440 | Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral) |
| 7441 | << ArgType << Arg->getSourceRange(); |
| 7442 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7443 | return ExprError(); |
| 7444 | } else if (!Arg->isValueDependent()) { |
| 7445 | class TmplArgICEDiagnoser : public VerifyICEDiagnoser { |
| 7446 | QualType T; |
| 7447 | |
| 7448 | public: |
| 7449 | TmplArgICEDiagnoser(QualType T) : T(T) { } |
| 7450 | |
| 7451 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, |
| 7452 | SourceLocation Loc) override { |
| 7453 | return S.Diag(Loc, diag::err_template_arg_not_ice) << T; |
| 7454 | } |
| 7455 | } Diagnoser(ArgType); |
| 7456 | |
| 7457 | Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get(); |
| 7458 | if (!Arg) |
| 7459 | return ExprError(); |
| 7460 | } |
| 7461 | |
| 7462 | // From here on out, all we care about is the unqualified form |
| 7463 | // of the argument type. |
| 7464 | ArgType = ArgType.getUnqualifiedType(); |
| 7465 | |
| 7466 | // Try to convert the argument to the parameter's type. |
| 7467 | if (Context.hasSameType(ParamType, ArgType)) { |
| 7468 | // Okay: no conversion necessary |
| 7469 | } else if (ParamType->isBooleanType()) { |
| 7470 | // This is an integral-to-boolean conversion. |
| 7471 | Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get(); |
| 7472 | } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || |
| 7473 | !ParamType->isEnumeralType()) { |
| 7474 | // This is an integral promotion or conversion. |
| 7475 | Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get(); |
| 7476 | } else { |
| 7477 | // We can't perform this conversion. |
| 7478 | Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) |
| 7479 | << Arg->getType() << ParamType << Arg->getSourceRange(); |
| 7480 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7481 | return ExprError(); |
| 7482 | } |
| 7483 | |
| 7484 | // Add the value of this argument to the list of converted |
| 7485 | // arguments. We use the bitwidth and signedness of the template |
| 7486 | // parameter. |
| 7487 | if (Arg->isValueDependent()) { |
| 7488 | // The argument is value-dependent. Create a new |
| 7489 | // TemplateArgument with the converted expression. |
| 7490 | SugaredConverted = TemplateArgument(Arg); |
| 7491 | CanonicalConverted = |
| 7492 | Context.getCanonicalTemplateArgument(SugaredConverted); |
| 7493 | return Arg; |
| 7494 | } |
| 7495 | |
| 7496 | QualType IntegerType = ParamType; |
| 7497 | if (const EnumType *Enum = IntegerType->getAs<EnumType>()) { |
| 7498 | IntegerType = Enum->getDecl()->getIntegerType(); |
| 7499 | } |
| 7500 | |
| 7501 | if (ParamType->isBooleanType()) { |
| 7502 | // Value must be zero or one. |
| 7503 | Value = Value != 0; |
| 7504 | unsigned AllowedBits = Context.getTypeSize(IntegerType); |
| 7505 | if (Value.getBitWidth() != AllowedBits) |
| 7506 | Value = Value.extOrTrunc(AllowedBits); |
| 7507 | Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); |
| 7508 | } else { |
| 7509 | llvm::APSInt OldValue = Value; |
| 7510 | |
| 7511 | // Coerce the template argument's value to the value it will have |
| 7512 | // based on the template parameter's type. |
| 7513 | unsigned AllowedBits = IntegerType->isBitIntType() |
| 7514 | ? Context.getIntWidth(IntegerType) |
| 7515 | : Context.getTypeSize(IntegerType); |
| 7516 | if (Value.getBitWidth() != AllowedBits) |
| 7517 | Value = Value.extOrTrunc(AllowedBits); |
| 7518 | Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); |
| 7519 | |
| 7520 | // Complain if an unsigned parameter received a negative value. |
| 7521 | if (IntegerType->isUnsignedIntegerOrEnumerationType() && |
| 7522 | (OldValue.isSigned() && OldValue.isNegative())) { |
| 7523 | Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative) |
| 7524 | << toString(OldValue, 10) << toString(Value, 10) << Param->getType() |
| 7525 | << Arg->getSourceRange(); |
| 7526 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7527 | } |
| 7528 | |
| 7529 | // Complain if we overflowed the template parameter's type. |
| 7530 | unsigned RequiredBits; |
| 7531 | if (IntegerType->isUnsignedIntegerOrEnumerationType()) |
| 7532 | RequiredBits = OldValue.getActiveBits(); |
| 7533 | else if (OldValue.isUnsigned()) |
| 7534 | RequiredBits = OldValue.getActiveBits() + 1; |
| 7535 | else |
| 7536 | RequiredBits = OldValue.getSignificantBits(); |
| 7537 | if (RequiredBits > AllowedBits) { |
| 7538 | Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large) |
| 7539 | << toString(OldValue, 10) << toString(Value, 10) << Param->getType() |
| 7540 | << Arg->getSourceRange(); |
| 7541 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7542 | } |
| 7543 | } |
| 7544 | |
| 7545 | QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType; |
| 7546 | SugaredConverted = TemplateArgument(Context, Value, T); |
| 7547 | CanonicalConverted = |
| 7548 | TemplateArgument(Context, Value, Context.getCanonicalType(T)); |
| 7549 | return Arg; |
| 7550 | } |
| 7551 | |
| 7552 | QualType ArgType = Arg->getType(); |
| 7553 | DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction |
| 7554 | |
| 7555 | // Handle pointer-to-function, reference-to-function, and |
| 7556 | // pointer-to-member-function all in (roughly) the same way. |
| 7557 | if (// -- For a non-type template-parameter of type pointer to |
| 7558 | // function, only the function-to-pointer conversion (4.3) is |
| 7559 | // applied. If the template-argument represents a set of |
| 7560 | // overloaded functions (or a pointer to such), the matching |
| 7561 | // function is selected from the set (13.4). |
| 7562 | (ParamType->isPointerType() && |
| 7563 | ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) || |
| 7564 | // -- For a non-type template-parameter of type reference to |
| 7565 | // function, no conversions apply. If the template-argument |
| 7566 | // represents a set of overloaded functions, the matching |
| 7567 | // function is selected from the set (13.4). |
| 7568 | (ParamType->isReferenceType() && |
| 7569 | ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) || |
| 7570 | // -- For a non-type template-parameter of type pointer to |
| 7571 | // member function, no conversions apply. If the |
| 7572 | // template-argument represents a set of overloaded member |
| 7573 | // functions, the matching member function is selected from |
| 7574 | // the set (13.4). |
| 7575 | (ParamType->isMemberPointerType() && |
| 7576 | ParamType->castAs<MemberPointerType>()->getPointeeType() |
| 7577 | ->isFunctionType())) { |
| 7578 | |
| 7579 | if (Arg->getType() == Context.OverloadTy) { |
| 7580 | if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, |
| 7581 | true, |
| 7582 | FoundResult)) { |
| 7583 | if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) |
| 7584 | return ExprError(); |
| 7585 | |
| 7586 | Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); |
| 7587 | ArgType = Arg->getType(); |
| 7588 | } else |
| 7589 | return ExprError(); |
| 7590 | } |
| 7591 | |
| 7592 | if (!ParamType->isMemberPointerType()) { |
| 7593 | if (CheckTemplateArgumentAddressOfObjectOrFunction( |
| 7594 | *this, Param, ParamType, Arg, SugaredConverted, |
| 7595 | CanonicalConverted)) |
| 7596 | return ExprError(); |
| 7597 | return Arg; |
| 7598 | } |
| 7599 | |
| 7600 | if (CheckTemplateArgumentPointerToMember( |
| 7601 | *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) |
| 7602 | return ExprError(); |
| 7603 | return Arg; |
| 7604 | } |
| 7605 | |
| 7606 | if (ParamType->isPointerType()) { |
| 7607 | // -- for a non-type template-parameter of type pointer to |
| 7608 | // object, qualification conversions (4.4) and the |
| 7609 | // array-to-pointer conversion (4.2) are applied. |
| 7610 | // C++0x also allows a value of std::nullptr_t. |
| 7611 | assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&(static_cast <bool> (ParamType->getPointeeType()-> isIncompleteOrObjectType() && "Only object pointers allowed here" ) ? void (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7612, __extension__ __PRETTY_FUNCTION__ )) |
| 7612 | "Only object pointers allowed here")(static_cast <bool> (ParamType->getPointeeType()-> isIncompleteOrObjectType() && "Only object pointers allowed here" ) ? void (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7612, __extension__ __PRETTY_FUNCTION__ )); |
| 7613 | |
| 7614 | if (CheckTemplateArgumentAddressOfObjectOrFunction( |
| 7615 | *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) |
| 7616 | return ExprError(); |
| 7617 | return Arg; |
| 7618 | } |
| 7619 | |
| 7620 | if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { |
| 7621 | // -- For a non-type template-parameter of type reference to |
| 7622 | // object, no conversions apply. The type referred to by the |
| 7623 | // reference may be more cv-qualified than the (otherwise |
| 7624 | // identical) type of the template-argument. The |
| 7625 | // template-parameter is bound directly to the |
| 7626 | // template-argument, which must be an lvalue. |
| 7627 | assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&(static_cast <bool> (ParamRefType->getPointeeType()-> isIncompleteOrObjectType() && "Only object references allowed here" ) ? void (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7628, __extension__ __PRETTY_FUNCTION__ )) |
| 7628 | "Only object references allowed here")(static_cast <bool> (ParamRefType->getPointeeType()-> isIncompleteOrObjectType() && "Only object references allowed here" ) ? void (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7628, __extension__ __PRETTY_FUNCTION__ )); |
| 7629 | |
| 7630 | if (Arg->getType() == Context.OverloadTy) { |
| 7631 | if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, |
| 7632 | ParamRefType->getPointeeType(), |
| 7633 | true, |
| 7634 | FoundResult)) { |
| 7635 | if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) |
| 7636 | return ExprError(); |
| 7637 | |
| 7638 | Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); |
| 7639 | ArgType = Arg->getType(); |
| 7640 | } else |
| 7641 | return ExprError(); |
| 7642 | } |
| 7643 | |
| 7644 | if (CheckTemplateArgumentAddressOfObjectOrFunction( |
| 7645 | *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) |
| 7646 | return ExprError(); |
| 7647 | return Arg; |
| 7648 | } |
| 7649 | |
| 7650 | // Deal with parameters of type std::nullptr_t. |
| 7651 | if (ParamType->isNullPtrType()) { |
| 7652 | if (Arg->isTypeDependent() || Arg->isValueDependent()) { |
| 7653 | SugaredConverted = TemplateArgument(Arg); |
| 7654 | CanonicalConverted = |
| 7655 | Context.getCanonicalTemplateArgument(SugaredConverted); |
| 7656 | return Arg; |
| 7657 | } |
| 7658 | |
| 7659 | switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) { |
| 7660 | case NPV_NotNullPointer: |
| 7661 | Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible) |
| 7662 | << Arg->getType() << ParamType; |
| 7663 | Diag(Param->getLocation(), diag::note_template_param_here); |
| 7664 | return ExprError(); |
| 7665 | |
| 7666 | case NPV_Error: |
| 7667 | return ExprError(); |
| 7668 | |
| 7669 | case NPV_NullPointer: |
| 7670 | Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); |
| 7671 | SugaredConverted = TemplateArgument(ParamType, |
| 7672 | /*isNullPtr=*/true); |
| 7673 | CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType), |
| 7674 | /*isNullPtr=*/true); |
| 7675 | return Arg; |
| 7676 | } |
| 7677 | } |
| 7678 | |
| 7679 | // -- For a non-type template-parameter of type pointer to data |
| 7680 | // member, qualification conversions (4.4) are applied. |
| 7681 | assert(ParamType->isMemberPointerType() && "Only pointers to members remain")(static_cast <bool> (ParamType->isMemberPointerType( ) && "Only pointers to members remain") ? void (0) : __assert_fail ("ParamType->isMemberPointerType() && \"Only pointers to members remain\"" , "clang/lib/Sema/SemaTemplate.cpp", 7681, __extension__ __PRETTY_FUNCTION__ )); |
| 7682 | |
| 7683 | if (CheckTemplateArgumentPointerToMember( |
| 7684 | *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) |
| 7685 | return ExprError(); |
| 7686 | return Arg; |
| 7687 | } |
| 7688 | |
| 7689 | static void DiagnoseTemplateParameterListArityMismatch( |
| 7690 | Sema &S, TemplateParameterList *New, TemplateParameterList *Old, |
| 7691 | Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc); |
| 7692 | |
| 7693 | /// Check a template argument against its corresponding |
| 7694 | /// template template parameter. |
| 7695 | /// |
| 7696 | /// This routine implements the semantics of C++ [temp.arg.template]. |
| 7697 | /// It returns true if an error occurred, and false otherwise. |
| 7698 | bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, |
| 7699 | TemplateParameterList *Params, |
| 7700 | TemplateArgumentLoc &Arg) { |
| 7701 | TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern(); |
| 7702 | TemplateDecl *Template = Name.getAsTemplateDecl(); |
| 7703 | if (!Template) { |
| 7704 | // Any dependent template name is fine. |
| 7705 | assert(Name.isDependent() && "Non-dependent template isn't a declaration?")(static_cast <bool> (Name.isDependent() && "Non-dependent template isn't a declaration?" ) ? void (0) : __assert_fail ("Name.isDependent() && \"Non-dependent template isn't a declaration?\"" , "clang/lib/Sema/SemaTemplate.cpp", 7705, __extension__ __PRETTY_FUNCTION__ )); |
| 7706 | return false; |
| 7707 | } |
| 7708 | |
| 7709 | if (Template->isInvalidDecl()) |
| 7710 | return true; |
| 7711 | |
| 7712 | // C++0x [temp.arg.template]p1: |
| 7713 | // A template-argument for a template template-parameter shall be |
| 7714 | // the name of a class template or an alias template, expressed as an |
| 7715 | // id-expression. When the template-argument names a class template, only |
| 7716 | // primary class templates are considered when matching the |
| 7717 | // template template argument with the corresponding parameter; |
| 7718 | // partial specializations are not considered even if their |
| 7719 | // parameter lists match that of the template template parameter. |
| 7720 | // |
| 7721 | // Note that we also allow template template parameters here, which |
| 7722 | // will happen when we are dealing with, e.g., class template |
| 7723 | // partial specializations. |
| 7724 | if (!isa<ClassTemplateDecl>(Template) && |
| 7725 | !isa<TemplateTemplateParmDecl>(Template) && |
| 7726 | !isa<TypeAliasTemplateDecl>(Template) && |
| 7727 | !isa<BuiltinTemplateDecl>(Template)) { |
| 7728 | assert(isa<FunctionTemplateDecl>(Template) &&(static_cast <bool> (isa<FunctionTemplateDecl>(Template ) && "Only function templates are possible here") ? void (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7729, __extension__ __PRETTY_FUNCTION__ )) |
| 7729 | "Only function templates are possible here")(static_cast <bool> (isa<FunctionTemplateDecl>(Template ) && "Only function templates are possible here") ? void (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7729, __extension__ __PRETTY_FUNCTION__ )); |
| 7730 | Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template); |
| 7731 | Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) |
| 7732 | << Template; |
| 7733 | } |
| 7734 | |
| 7735 | // C++1z [temp.arg.template]p3: (DR 150) |
| 7736 | // A template-argument matches a template template-parameter P when P |
| 7737 | // is at least as specialized as the template-argument A. |
| 7738 | // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a |
| 7739 | // defect report resolution from C++17 and shouldn't be introduced by |
| 7740 | // concepts. |
| 7741 | if (getLangOpts().RelaxedTemplateTemplateArgs) { |
| 7742 | // Quick check for the common case: |
| 7743 | // If P contains a parameter pack, then A [...] matches P if each of A's |
| 7744 | // template parameters matches the corresponding template parameter in |
| 7745 | // the template-parameter-list of P. |
| 7746 | if (TemplateParameterListsAreEqual( |
| 7747 | Template->getTemplateParameters(), Params, false, |
| 7748 | TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) && |
| 7749 | // If the argument has no associated constraints, then the parameter is |
| 7750 | // definitely at least as specialized as the argument. |
| 7751 | // Otherwise - we need a more thorough check. |
| 7752 | !Template->hasAssociatedConstraints()) |
| 7753 | return false; |
| 7754 | |
| 7755 | if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template, |
| 7756 | Arg.getLocation())) { |
| 7757 | // P2113 |
| 7758 | // C++20[temp.func.order]p2 |
| 7759 | // [...] If both deductions succeed, the partial ordering selects the |
| 7760 | // more constrained template (if one exists) as determined below. |
| 7761 | SmallVector<const Expr *, 3> ParamsAC, TemplateAC; |
| 7762 | Params->getAssociatedConstraints(ParamsAC); |
| 7763 | // C++2a[temp.arg.template]p3 |
| 7764 | // [...] In this comparison, if P is unconstrained, the constraints on A |
| 7765 | // are not considered. |
| 7766 | if (ParamsAC.empty()) |
| 7767 | return false; |
| 7768 | |
| 7769 | Template->getAssociatedConstraints(TemplateAC); |
| 7770 | |
| 7771 | bool IsParamAtLeastAsConstrained; |
| 7772 | if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC, |
| 7773 | IsParamAtLeastAsConstrained)) |
| 7774 | return true; |
| 7775 | if (!IsParamAtLeastAsConstrained) { |
| 7776 | Diag(Arg.getLocation(), |
| 7777 | diag::err_template_template_parameter_not_at_least_as_constrained) |
| 7778 | << Template << Param << Arg.getSourceRange(); |
| 7779 | Diag(Param->getLocation(), diag::note_entity_declared_at) << Param; |
| 7780 | Diag(Template->getLocation(), diag::note_entity_declared_at) |
| 7781 | << Template; |
| 7782 | MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template, |
| 7783 | TemplateAC); |
| 7784 | return true; |
| 7785 | } |
| 7786 | return false; |
| 7787 | } |
| 7788 | // FIXME: Produce better diagnostics for deduction failures. |
| 7789 | } |
| 7790 | |
| 7791 | return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), |
| 7792 | Params, |
| 7793 | true, |
| 7794 | TPL_TemplateTemplateArgumentMatch, |
| 7795 | Arg.getLocation()); |
| 7796 | } |
| 7797 | |
| 7798 | /// Given a non-type template argument that refers to a |
| 7799 | /// declaration and the type of its corresponding non-type template |
| 7800 | /// parameter, produce an expression that properly refers to that |
| 7801 | /// declaration. |
| 7802 | ExprResult |
| 7803 | Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, |
| 7804 | QualType ParamType, |
| 7805 | SourceLocation Loc) { |
| 7806 | // C++ [temp.param]p8: |
| 7807 | // |
| 7808 | // A non-type template-parameter of type "array of T" or |
| 7809 | // "function returning T" is adjusted to be of type "pointer to |
| 7810 | // T" or "pointer to function returning T", respectively. |
| 7811 | if (ParamType->isArrayType()) |
| 7812 | ParamType = Context.getArrayDecayedType(ParamType); |
| 7813 | else if (ParamType->isFunctionType()) |
| 7814 | ParamType = Context.getPointerType(ParamType); |
| 7815 | |
| 7816 | // For a NULL non-type template argument, return nullptr casted to the |
| 7817 | // parameter's type. |
| 7818 | if (Arg.getKind() == TemplateArgument::NullPtr) { |
| 7819 | return ImpCastExprToType( |
| 7820 | new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc), |
| 7821 | ParamType, |
| 7822 | ParamType->getAs<MemberPointerType>() |
| 7823 | ? CK_NullToMemberPointer |
| 7824 | : CK_NullToPointer); |
| 7825 | } |
| 7826 | assert(Arg.getKind() == TemplateArgument::Declaration &&(static_cast <bool> (Arg.getKind() == TemplateArgument:: Declaration && "Only declaration template arguments permitted here" ) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7827, __extension__ __PRETTY_FUNCTION__ )) |
| 7827 | "Only declaration template arguments permitted here")(static_cast <bool> (Arg.getKind() == TemplateArgument:: Declaration && "Only declaration template arguments permitted here" ) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\"" , "clang/lib/Sema/SemaTemplate.cpp", 7827, __extension__ __PRETTY_FUNCTION__ )); |
| 7828 | |
| 7829 | ValueDecl *VD = Arg.getAsDecl(); |
| 7830 | |
| 7831 | CXXScopeSpec SS; |
| 7832 | if (ParamType->isMemberPointerType()) { |
| 7833 | // If this is a pointer to member, we need to use a qualified name to |
| 7834 | // form a suitable pointer-to-member constant. |
| 7835 | assert(VD->getDeclContext()->isRecord() &&(static_cast <bool> (VD->getDeclContext()->isRecord () && (isa<CXXMethodDecl>(VD) || isa<FieldDecl >(VD) || isa<IndirectFieldDecl>(VD))) ? void (0) : __assert_fail ("VD->getDeclContext()->isRecord() && (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))" , "clang/lib/Sema/SemaTemplate.cpp", 7837, __extension__ __PRETTY_FUNCTION__ )) |
| 7836 | (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||(static_cast <bool> (VD->getDeclContext()->isRecord () && (isa<CXXMethodDecl>(VD) || isa<FieldDecl >(VD) || isa<IndirectFieldDecl>(VD))) ? void (0) : __assert_fail ("VD->getDeclContext()->isRecord() && (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))" , "clang/lib/Sema/SemaTemplate.cpp", 7837, __extension__ __PRETTY_FUNCTION__ )) |
| 7837 | isa<IndirectFieldDecl>(VD)))(static_cast <bool> (VD->getDeclContext()->isRecord () && (isa<CXXMethodDecl>(VD) || isa<FieldDecl >(VD) || isa<IndirectFieldDecl>(VD))) ? void (0) : __assert_fail ("VD->getDeclContext()->isRecord() && (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))" , "clang/lib/Sema/SemaTemplate.cpp", 7837, __extension__ __PRETTY_FUNCTION__ )); |
| 7838 | QualType ClassType |
| 7839 | = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); |
| 7840 | NestedNameSpecifier *Qualifier |
| 7841 | = NestedNameSpecifier::Create(Context, nullptr, false, |
| 7842 | ClassType.getTypePtr()); |
| 7843 | SS.MakeTrivial(Context, Qualifier, Loc); |
| 7844 | } |
| 7845 | |
| 7846 | ExprResult RefExpr = BuildDeclarationNameExpr( |
| 7847 | SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD); |
| 7848 | if (RefExpr.isInvalid()) |
| 7849 | return ExprError(); |
| 7850 | |
| 7851 | // For a pointer, the argument declaration is the pointee. Take its address. |
| 7852 | QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0); |
| 7853 | if (ParamType->isPointerType() && !ElemT.isNull() && |
| 7854 | Context.hasSimilarType(ElemT, ParamType->getPointeeType())) { |
| 7855 | // Decay an array argument if we want a pointer to its first element. |
| 7856 | RefExpr = DefaultFunctionArrayConversion(RefExpr.get()); |
| 7857 | if (RefExpr.isInvalid()) |
| 7858 | return ExprError(); |
| 7859 | } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) { |
| 7860 | // For any other pointer, take the address (or form a pointer-to-member). |
| 7861 | RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); |
| 7862 | if (RefExpr.isInvalid()) |
| 7863 | return ExprError(); |
| 7864 | } else if (ParamType->isRecordType()) { |
| 7865 | assert(isa<TemplateParamObjectDecl>(VD) &&(static_cast <bool> (isa<TemplateParamObjectDecl> (VD) && "arg for class template param not a template parameter object" ) ? void (0) : __assert_fail ("isa<TemplateParamObjectDecl>(VD) && \"arg for class template param not a template parameter object\"" , "clang/lib/Sema/SemaTemplate.cpp", 7866, __extension__ __PRETTY_FUNCTION__ )) |
| 7866 | "arg for class template param not a template parameter object")(static_cast <bool> (isa<TemplateParamObjectDecl> (VD) && "arg for class template param not a template parameter object" ) ? void (0) : __assert_fail ("isa<TemplateParamObjectDecl>(VD) && \"arg for class template param not a template parameter object\"" , "clang/lib/Sema/SemaTemplate.cpp", 7866, __extension__ __PRETTY_FUNCTION__ )); |
| 7867 | // No conversions apply in this case. |
| 7868 | return RefExpr; |
| 7869 | } else { |
| 7870 | assert(ParamType->isReferenceType() &&(static_cast <bool> (ParamType->isReferenceType() && "unexpected type for decl template argument") ? void (0) : __assert_fail ("ParamType->isReferenceType() && \"unexpected type for decl template argument\"" , "clang/lib/Sema/SemaTemplate.cpp", 7871, __extension__ __PRETTY_FUNCTION__ )) |
| 7871 | "unexpected type for decl template argument")(static_cast <bool> (ParamType->isReferenceType() && "unexpected type for decl template argument") ? void (0) : __assert_fail ("ParamType->isReferenceType() && \"unexpected type for decl template argument\"" , "clang/lib/Sema/SemaTemplate.cpp", 7871, __extension__ __PRETTY_FUNCTION__ )); |
| 7872 | } |
| 7873 | |
| 7874 | // At this point we should have the right value category. |
| 7875 | assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&(static_cast <bool> (ParamType->isReferenceType() == RefExpr.get()->isLValue() && "value kind mismatch for non-type template argument" ) ? void (0) : __assert_fail ("ParamType->isReferenceType() == RefExpr.get()->isLValue() && \"value kind mismatch for non-type template argument\"" , "clang/lib/Sema/SemaTemplate.cpp", 7876, __extension__ __PRETTY_FUNCTION__ )) |
| 7876 | "value kind mismatch for non-type template argument")(static_cast <bool> (ParamType->isReferenceType() == RefExpr.get()->isLValue() && "value kind mismatch for non-type template argument" ) ? void (0) : __assert_fail ("ParamType->isReferenceType() == RefExpr.get()->isLValue() && \"value kind mismatch for non-type template argument\"" , "clang/lib/Sema/SemaTemplate.cpp", 7876, __extension__ __PRETTY_FUNCTION__ )); |
| 7877 | |
| 7878 | // The type of the template parameter can differ from the type of the |
| 7879 | // argument in various ways; convert it now if necessary. |
| 7880 | QualType DestExprType = ParamType.getNonLValueExprType(Context); |
| 7881 | if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) { |
| 7882 | CastKind CK; |
| 7883 | QualType Ignored; |
| 7884 | if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) || |
| 7885 | IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) { |
| 7886 | CK = CK_NoOp; |
| 7887 | } else if (ParamType->isVoidPointerType() && |
| 7888 | RefExpr.get()->getType()->isPointerType()) { |
| 7889 | CK = CK_BitCast; |
| 7890 | } else { |
| 7891 | // FIXME: Pointers to members can need conversion derived-to-base or |
| 7892 | // base-to-derived conversions. We currently don't retain enough |
| 7893 | // information to convert properly (we need to track a cast path or |
| 7894 | // subobject number in the template argument). |
| 7895 | llvm_unreachable(::llvm::llvm_unreachable_internal("unexpected conversion required for non-type template argument" , "clang/lib/Sema/SemaTemplate.cpp", 7896) |
| 7896 | "unexpected conversion required for non-type template argument")::llvm::llvm_unreachable_internal("unexpected conversion required for non-type template argument" , "clang/lib/Sema/SemaTemplate.cpp", 7896); |
| 7897 | } |
| 7898 | RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK, |
| 7899 | RefExpr.get()->getValueKind()); |
| 7900 | } |
| 7901 | |
| 7902 | return RefExpr; |
| 7903 | } |
| 7904 | |
| 7905 | /// Construct a new expression that refers to the given |
| 7906 | /// integral template argument with the given source-location |
| 7907 | /// information. |
| 7908 | /// |
| 7909 | /// This routine takes care of the mapping from an integral template |
| 7910 | /// argument (which may have any integral type) to the appropriate |
| 7911 | /// literal value. |
| 7912 | ExprResult |
| 7913 | Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, |
| 7914 | SourceLocation Loc) { |
| 7915 | assert(Arg.getKind() == TemplateArgument::Integral &&(static_cast <bool> (Arg.getKind() == TemplateArgument:: Integral && "Operation is only valid for integral template arguments" ) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\"" , "clang/lib/Sema/SemaTemplate.cpp", 7916, __extension__ __PRETTY_FUNCTION__ )) |
| 7916 | "Operation is only valid for integral template arguments")(static_cast <bool> (Arg.getKind() == TemplateArgument:: Integral && "Operation is only valid for integral template arguments" ) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\"" , "clang/lib/Sema/SemaTemplate.cpp", 7916, __extension__ __PRETTY_FUNCTION__ )); |
| 7917 | QualType OrigT = Arg.getIntegralType(); |
| 7918 | |
| 7919 | // If this is an enum type that we're instantiating, we need to use an integer |
| 7920 | // type the same size as the enumerator. We don't want to build an |
| 7921 | // IntegerLiteral with enum type. The integer type of an enum type can be of |
| 7922 | // any integral type with C++11 enum classes, make sure we create the right |
| 7923 | // type of literal for it. |
| 7924 | QualType T = OrigT; |
| 7925 | if (const EnumType *ET = OrigT->getAs<EnumType>()) |
| 7926 | T = ET->getDecl()->getIntegerType(); |
| 7927 | |
| 7928 | Expr *E; |
| 7929 | if (T->isAnyCharacterType()) { |
| 7930 | CharacterLiteral::CharacterKind Kind; |
| 7931 | if (T->isWideCharType()) |
| 7932 | Kind = CharacterLiteral::Wide; |
| 7933 | else if (T->isChar8Type() && getLangOpts().Char8) |
| 7934 | Kind = CharacterLiteral::UTF8; |
| 7935 | else if (T->isChar16Type()) |
| 7936 | Kind = CharacterLiteral::UTF16; |
| 7937 | else if (T->isChar32Type()) |
| 7938 | Kind = CharacterLiteral::UTF32; |
| 7939 | else |
| 7940 | Kind = CharacterLiteral::Ascii; |
| 7941 | |
| 7942 | E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(), |
| 7943 | Kind, T, Loc); |
| 7944 | } else if (T->isBooleanType()) { |
| 7945 | E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(), |
| 7946 | T, Loc); |
| 7947 | } else if (T->isNullPtrType()) { |
| 7948 | E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); |
| 7949 | } else { |
| 7950 | E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc); |
| 7951 | } |
| 7952 | |
| 7953 | if (OrigT->isEnumeralType()) { |
| 7954 | // FIXME: This is a hack. We need a better way to handle substituted |
| 7955 | // non-type template parameters. |
| 7956 | E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E, |
| 7957 | nullptr, CurFPFeatureOverrides(), |
| 7958 | Context.getTrivialTypeSourceInfo(OrigT, Loc), |
| 7959 | Loc, Loc); |
| 7960 | } |
| 7961 | |
| 7962 | return E; |
| 7963 | } |
| 7964 | |
| 7965 | /// Match two template parameters within template parameter lists. |
| 7966 | static bool MatchTemplateParameterKind( |
| 7967 | Sema &S, NamedDecl *New, const NamedDecl *NewInstFrom, NamedDecl *Old, |
| 7968 | const NamedDecl *OldInstFrom, bool Complain, |
| 7969 | Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { |
| 7970 | // Check the actual kind (type, non-type, template). |
| 7971 | if (Old->getKind() != New->getKind()) { |
| 7972 | if (Complain) { |
| 7973 | unsigned NextDiag = diag::err_template_param_different_kind; |
| 7974 | if (TemplateArgLoc.isValid()) { |
| 7975 | S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); |
| 7976 | NextDiag = diag::note_template_param_different_kind; |
| 7977 | } |
| 7978 | S.Diag(New->getLocation(), NextDiag) |
| 7979 | << (Kind != Sema::TPL_TemplateMatch); |
| 7980 | S.Diag(Old->getLocation(), diag::note_template_prev_declaration) |
| 7981 | << (Kind != Sema::TPL_TemplateMatch); |
| 7982 | } |
| 7983 | |
| 7984 | return false; |
| 7985 | } |
| 7986 | |
| 7987 | // Check that both are parameter packs or neither are parameter packs. |
| 7988 | // However, if we are matching a template template argument to a |
| 7989 | // template template parameter, the template template parameter can have |
| 7990 | // a parameter pack where the template template argument does not. |
| 7991 | if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && |
| 7992 | !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && |
| 7993 | Old->isTemplateParameterPack())) { |
| 7994 | if (Complain) { |
| 7995 | unsigned NextDiag = diag::err_template_parameter_pack_non_pack; |
| 7996 | if (TemplateArgLoc.isValid()) { |
| 7997 | S.Diag(TemplateArgLoc, |
| 7998 | diag::err_template_arg_template_params_mismatch); |
| 7999 | NextDiag = diag::note_template_parameter_pack_non_pack; |
| 8000 | } |
| 8001 | |
| 8002 | unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 |
| 8003 | : isa<NonTypeTemplateParmDecl>(New)? 1 |
| 8004 | : 2; |
| 8005 | S.Diag(New->getLocation(), NextDiag) |
| 8006 | << ParamKind << New->isParameterPack(); |
| 8007 | S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) |
| 8008 | << ParamKind << Old->isParameterPack(); |
| 8009 | } |
| 8010 | |
| 8011 | return false; |
| 8012 | } |
| 8013 | |
| 8014 | // For non-type template parameters, check the type of the parameter. |
| 8015 | if (NonTypeTemplateParmDecl *OldNTTP |
| 8016 | = dyn_cast<NonTypeTemplateParmDecl>(Old)) { |
| 8017 | NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); |
| 8018 | |
| 8019 | // If we are matching a template template argument to a template |
| 8020 | // template parameter and one of the non-type template parameter types |
| 8021 | // is dependent, then we must wait until template instantiation time |
| 8022 | // to actually compare the arguments. |
| 8023 | if (Kind != Sema::TPL_TemplateTemplateArgumentMatch || |
| 8024 | (!OldNTTP->getType()->isDependentType() && |
| 8025 | !NewNTTP->getType()->isDependentType())) { |
| 8026 | // C++20 [temp.over.link]p6: |
| 8027 | // Two [non-type] template-parameters are equivalent [if] they have |
| 8028 | // equivalent types ignoring the use of type-constraints for |
| 8029 | // placeholder types |
| 8030 | QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType()); |
| 8031 | QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType()); |
| 8032 | if (!S.Context.hasSameType(OldType, NewType)) { |
| 8033 | if (Complain) { |
| 8034 | unsigned NextDiag = diag::err_template_nontype_parm_different_type; |
| 8035 | if (TemplateArgLoc.isValid()) { |
| 8036 | S.Diag(TemplateArgLoc, |
| 8037 | diag::err_template_arg_template_params_mismatch); |
| 8038 | NextDiag = diag::note_template_nontype_parm_different_type; |
| 8039 | } |
| 8040 | S.Diag(NewNTTP->getLocation(), NextDiag) |
| 8041 | << NewNTTP->getType() |
| 8042 | << (Kind != Sema::TPL_TemplateMatch); |
| 8043 | S.Diag(OldNTTP->getLocation(), |
| 8044 | diag::note_template_nontype_parm_prev_declaration) |
| 8045 | << OldNTTP->getType(); |
| 8046 | } |
| 8047 | |
| 8048 | return false; |
| 8049 | } |
| 8050 | } |
| 8051 | } |
| 8052 | // For template template parameters, check the template parameter types. |
| 8053 | // The template parameter lists of template template |
| 8054 | // parameters must agree. |
| 8055 | else if (TemplateTemplateParmDecl *OldTTP |
| 8056 | = dyn_cast<TemplateTemplateParmDecl>(Old)) { |
| 8057 | TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); |
| 8058 | if (!S.TemplateParameterListsAreEqual( |
| 8059 | NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom, |
| 8060 | OldTTP->getTemplateParameters(), Complain, |
| 8061 | (Kind == Sema::TPL_TemplateMatch |
| 8062 | ? Sema::TPL_TemplateTemplateParmMatch |
| 8063 | : Kind), |
| 8064 | TemplateArgLoc)) |
| 8065 | return false; |
| 8066 | } |
| 8067 | |
| 8068 | if (Kind != Sema::TPL_TemplateParamsEquivalent && |
| 8069 | Kind != Sema::TPL_TemplateTemplateArgumentMatch && |
| 8070 | !isa<TemplateTemplateParmDecl>(Old)) { |
| 8071 | const Expr *NewC = nullptr, *OldC = nullptr; |
| 8072 | |
| 8073 | if (isa<TemplateTypeParmDecl>(New)) { |
| 8074 | if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint()) |
| 8075 | NewC = TC->getImmediatelyDeclaredConstraint(); |
| 8076 | if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint()) |
| 8077 | OldC = TC->getImmediatelyDeclaredConstraint(); |
| 8078 | } else if (isa<NonTypeTemplateParmDecl>(New)) { |
| 8079 | if (const Expr *E = cast<NonTypeTemplateParmDecl>(New) |
| 8080 | ->getPlaceholderTypeConstraint()) |
| 8081 | NewC = E; |
| 8082 | if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old) |
| 8083 | ->getPlaceholderTypeConstraint()) |
| 8084 | OldC = E; |
| 8085 | } else |
| 8086 | llvm_unreachable("unexpected template parameter type")::llvm::llvm_unreachable_internal("unexpected template parameter type" , "clang/lib/Sema/SemaTemplate.cpp", 8086); |
| 8087 | |
| 8088 | auto Diagnose = [&] { |
| 8089 | S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(), |
| 8090 | diag::err_template_different_type_constraint); |
| 8091 | S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(), |
| 8092 | diag::note_template_prev_declaration) << /*declaration*/0; |
| 8093 | }; |
| 8094 | |
| 8095 | if (!NewC != !OldC) { |
| 8096 | if (Complain) |
| 8097 | Diagnose(); |
| 8098 | return false; |
| 8099 | } |
| 8100 | |
| 8101 | if (NewC) { |
| 8102 | if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom, |
| 8103 | NewC)) { |
| 8104 | if (Complain) |
| 8105 | Diagnose(); |
| 8106 | return false; |
| 8107 | } |
| 8108 | } |
| 8109 | } |
| 8110 | |
| 8111 | return true; |
| 8112 | } |
| 8113 | |
| 8114 | /// Diagnose a known arity mismatch when comparing template argument |
| 8115 | /// lists. |
| 8116 | static |
| 8117 | void DiagnoseTemplateParameterListArityMismatch(Sema &S, |
| 8118 | TemplateParameterList *New, |
| 8119 | TemplateParameterList *Old, |
| 8120 | Sema::TemplateParameterListEqualKind Kind, |
| 8121 | SourceLocation TemplateArgLoc) { |
| 8122 | unsigned NextDiag = diag::err_template_param_list_different_arity; |
| 8123 | if (TemplateArgLoc.isValid()) { |
| 8124 | S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); |
| 8125 | NextDiag = diag::note_template_param_list_different_arity; |
| 8126 | } |
| 8127 | S.Diag(New->getTemplateLoc(), NextDiag) |
| 8128 | << (New->size() > Old->size()) |
| 8129 | << (Kind != Sema::TPL_TemplateMatch) |
| 8130 | << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); |
| 8131 | S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) |
| 8132 | << (Kind != Sema::TPL_TemplateMatch) |
| 8133 | << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); |
| 8134 | } |
| 8135 | |
| 8136 | /// Determine whether the given template parameter lists are |
| 8137 | /// equivalent. |
| 8138 | /// |
| 8139 | /// \param New The new template parameter list, typically written in the |
| 8140 | /// source code as part of a new template declaration. |
| 8141 | /// |
| 8142 | /// \param Old The old template parameter list, typically found via |
| 8143 | /// name lookup of the template declared with this template parameter |
| 8144 | /// list. |
| 8145 | /// |
| 8146 | /// \param Complain If true, this routine will produce a diagnostic if |
| 8147 | /// the template parameter lists are not equivalent. |
| 8148 | /// |
| 8149 | /// \param Kind describes how we are to match the template parameter lists. |
| 8150 | /// |
| 8151 | /// \param TemplateArgLoc If this source location is valid, then we |
| 8152 | /// are actually checking the template parameter list of a template |
| 8153 | /// argument (New) against the template parameter list of its |
| 8154 | /// corresponding template template parameter (Old). We produce |
| 8155 | /// slightly different diagnostics in this scenario. |
| 8156 | /// |
| 8157 | /// \returns True if the template parameter lists are equal, false |
| 8158 | /// otherwise. |
| 8159 | bool Sema::TemplateParameterListsAreEqual( |
| 8160 | const NamedDecl *NewInstFrom, TemplateParameterList *New, |
| 8161 | const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, |
| 8162 | TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { |
| 8163 | if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { |
| 8164 | if (Complain) |
| 8165 | DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, |
| 8166 | TemplateArgLoc); |
| 8167 | |
| 8168 | return false; |
| 8169 | } |
| 8170 | |
| 8171 | // C++0x [temp.arg.template]p3: |
| 8172 | // A template-argument matches a template template-parameter (call it P) |
| 8173 | // when each of the template parameters in the template-parameter-list of |
| 8174 | // the template-argument's corresponding class template or alias template |
| 8175 | // (call it A) matches the corresponding template parameter in the |
| 8176 | // template-parameter-list of P. [...] |
| 8177 | TemplateParameterList::iterator NewParm = New->begin(); |
| 8178 | TemplateParameterList::iterator NewParmEnd = New->end(); |
| 8179 | for (TemplateParameterList::iterator OldParm = Old->begin(), |
| 8180 | OldParmEnd = Old->end(); |
| 8181 | OldParm != OldParmEnd; ++OldParm) { |
| 8182 | if (Kind != TPL_TemplateTemplateArgumentMatch || |
| 8183 | !(*OldParm)->isTemplateParameterPack()) { |
| 8184 | if (NewParm == NewParmEnd) { |
| 8185 | if (Complain) |
| 8186 | DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, |
| 8187 | TemplateArgLoc); |
| 8188 | |
| 8189 | return false; |
| 8190 | } |
| 8191 | |
| 8192 | if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm, |
| 8193 | OldInstFrom, Complain, Kind, |
| 8194 | TemplateArgLoc)) |
| 8195 | return false; |
| 8196 | |
| 8197 | ++NewParm; |
| 8198 | continue; |
| 8199 | } |
| 8200 | |
| 8201 | // C++0x [temp.arg.template]p3: |
| 8202 | // [...] When P's template- parameter-list contains a template parameter |
| 8203 | // pack (14.5.3), the template parameter pack will match zero or more |
| 8204 | // template parameters or template parameter packs in the |
| 8205 | // template-parameter-list of A with the same type and form as the |
| 8206 | // template parameter pack in P (ignoring whether those template |
| 8207 | // parameters are template parameter packs). |
| 8208 | for (; NewParm != NewParmEnd; ++NewParm) { |
| 8209 | if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm, |
| 8210 | OldInstFrom, Complain, Kind, |
| 8211 | TemplateArgLoc)) |
| 8212 | return false; |
| 8213 | } |
| 8214 | } |
| 8215 | |
| 8216 | // Make sure we exhausted all of the arguments. |
| 8217 | if (NewParm != NewParmEnd) { |
| 8218 | if (Complain) |
| 8219 | DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, |
| 8220 | TemplateArgLoc); |
| 8221 | |
| 8222 | return false; |
| 8223 | } |
| 8224 | |
| 8225 | if (Kind != TPL_TemplateTemplateArgumentMatch && |
| 8226 | Kind != TPL_TemplateParamsEquivalent) { |
| 8227 | const Expr *NewRC = New->getRequiresClause(); |
| 8228 | const Expr *OldRC = Old->getRequiresClause(); |
| 8229 | |
| 8230 | auto Diagnose = [&] { |
| 8231 | Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(), |
| 8232 | diag::err_template_different_requires_clause); |
| 8233 | Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(), |
| 8234 | diag::note_template_prev_declaration) << /*declaration*/0; |
| 8235 | }; |
| 8236 | |
| 8237 | if (!NewRC != !OldRC) { |
| 8238 | if (Complain) |
| 8239 | Diagnose(); |
| 8240 | return false; |
| 8241 | } |
| 8242 | |
| 8243 | if (NewRC) { |
| 8244 | if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom, |
| 8245 | NewRC)) { |
| 8246 | if (Complain) |
| 8247 | Diagnose(); |
| 8248 | return false; |
| 8249 | } |
| 8250 | } |
| 8251 | } |
| 8252 | |
| 8253 | return true; |
| 8254 | } |
| 8255 | |
| 8256 | /// Check whether a template can be declared within this scope. |
| 8257 | /// |
| 8258 | /// If the template declaration is valid in this scope, returns |
| 8259 | /// false. Otherwise, issues a diagnostic and returns true. |
| 8260 | bool |
| 8261 | Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { |
| 8262 | if (!S) |
| 8263 | return false; |
| 8264 | |
| 8265 | // Find the nearest enclosing declaration scope. |
| 8266 | while ((S->getFlags() & Scope::DeclScope) == 0 || |
| 8267 | (S->getFlags() & Scope::TemplateParamScope) != 0) |
| 8268 | S = S->getParent(); |
| 8269 | |
| 8270 | // C++ [temp.pre]p6: [P2096] |
| 8271 | // A template, explicit specialization, or partial specialization shall not |
| 8272 | // have C linkage. |
| 8273 | DeclContext *Ctx = S->getEntity(); |
| 8274 | if (Ctx && Ctx->isExternCContext()) { |
| 8275 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) |
| 8276 | << TemplateParams->getSourceRange(); |
| 8277 | if (const LinkageSpecDecl *LSD = Ctx->getExternCContext()) |
| 8278 | Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); |
| 8279 | return true; |
| 8280 | } |
| 8281 | Ctx = Ctx ? Ctx->getRedeclContext() : nullptr; |
| 8282 | |
| 8283 | // C++ [temp]p2: |
| 8284 | // A template-declaration can appear only as a namespace scope or |
| 8285 | // class scope declaration. |
| 8286 | // C++ [temp.expl.spec]p3: |
| 8287 | // An explicit specialization may be declared in any scope in which the |
| 8288 | // corresponding primary template may be defined. |
| 8289 | // C++ [temp.class.spec]p6: [P2096] |
| 8290 | // A partial specialization may be declared in any scope in which the |
| 8291 | // corresponding primary template may be defined. |
| 8292 | if (Ctx) { |
| 8293 | if (Ctx->isFileContext()) |
| 8294 | return false; |
| 8295 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) { |
| 8296 | // C++ [temp.mem]p2: |
| 8297 | // A local class shall not have member templates. |
| 8298 | if (RD->isLocalClass()) |
| 8299 | return Diag(TemplateParams->getTemplateLoc(), |
| 8300 | diag::err_template_inside_local_class) |
| 8301 | << TemplateParams->getSourceRange(); |
| 8302 | else |
| 8303 | return false; |
| 8304 | } |
| 8305 | } |
| 8306 | |
| 8307 | return Diag(TemplateParams->getTemplateLoc(), |
| 8308 | diag::err_template_outside_namespace_or_class_scope) |
| 8309 | << TemplateParams->getSourceRange(); |
| 8310 | } |
| 8311 | |
| 8312 | /// Determine what kind of template specialization the given declaration |
| 8313 | /// is. |
| 8314 | static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) { |
| 8315 | if (!D) |
| 8316 | return TSK_Undeclared; |
| 8317 | |
| 8318 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) |
| 8319 | return Record->getTemplateSpecializationKind(); |
| 8320 | if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) |
| 8321 | return Function->getTemplateSpecializationKind(); |
| 8322 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) |
| 8323 | return Var->getTemplateSpecializationKind(); |
| 8324 | |
| 8325 | return TSK_Undeclared; |
| 8326 | } |
| 8327 | |
| 8328 | /// Check whether a specialization is well-formed in the current |
| 8329 | /// context. |
| 8330 | /// |
| 8331 | /// This routine determines whether a template specialization can be declared |
| 8332 | /// in the current context (C++ [temp.expl.spec]p2). |
| 8333 | /// |
| 8334 | /// \param S the semantic analysis object for which this check is being |
| 8335 | /// performed. |
| 8336 | /// |
| 8337 | /// \param Specialized the entity being specialized or instantiated, which |
| 8338 | /// may be a kind of template (class template, function template, etc.) or |
| 8339 | /// a member of a class template (member function, static data member, |
| 8340 | /// member class). |
| 8341 | /// |
| 8342 | /// \param PrevDecl the previous declaration of this entity, if any. |
| 8343 | /// |
| 8344 | /// \param Loc the location of the explicit specialization or instantiation of |
| 8345 | /// this entity. |
| 8346 | /// |
| 8347 | /// \param IsPartialSpecialization whether this is a partial specialization of |
| 8348 | /// a class template. |
| 8349 | /// |
| 8350 | /// \returns true if there was an error that we cannot recover from, false |
| 8351 | /// otherwise. |
| 8352 | static bool CheckTemplateSpecializationScope(Sema &S, |
| 8353 | NamedDecl *Specialized, |
| 8354 | NamedDecl *PrevDecl, |
| 8355 | SourceLocation Loc, |
| 8356 | bool IsPartialSpecialization) { |
| 8357 | // Keep these "kind" numbers in sync with the %select statements in the |
| 8358 | // various diagnostics emitted by this routine. |
| 8359 | int EntityKind = 0; |
| 8360 | if (isa<ClassTemplateDecl>(Specialized)) |
| 8361 | EntityKind = IsPartialSpecialization? 1 : 0; |
| 8362 | else if (isa<VarTemplateDecl>(Specialized)) |
| 8363 | EntityKind = IsPartialSpecialization ? 3 : 2; |
| 8364 | else if (isa<FunctionTemplateDecl>(Specialized)) |
| 8365 | EntityKind = 4; |
| 8366 | else if (isa<CXXMethodDecl>(Specialized)) |
| 8367 | EntityKind = 5; |
| 8368 | else if (isa<VarDecl>(Specialized)) |
| 8369 | EntityKind = 6; |
| 8370 | else if (isa<RecordDecl>(Specialized)) |
| 8371 | EntityKind = 7; |
| 8372 | else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11) |
| 8373 | EntityKind = 8; |
| 8374 | else { |
| 8375 | S.Diag(Loc, diag::err_template_spec_unknown_kind) |
| 8376 | << S.getLangOpts().CPlusPlus11; |
| 8377 | S.Diag(Specialized->getLocation(), diag::note_specialized_entity); |
| 8378 | return true; |
| 8379 | } |
| 8380 | |
| 8381 | // C++ [temp.expl.spec]p2: |
| 8382 | // An explicit specialization may be declared in any scope in which |
| 8383 | // the corresponding primary template may be defined. |
| 8384 | if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { |
| 8385 | S.Diag(Loc, diag::err_template_spec_decl_function_scope) |
| 8386 | << Specialized; |
| 8387 | return true; |
| 8388 | } |
| 8389 | |
| 8390 | // C++ [temp.class.spec]p6: |
| 8391 | // A class template partial specialization may be declared in any |
| 8392 | // scope in which the primary template may be defined. |
| 8393 | DeclContext *SpecializedContext = |
| 8394 | Specialized->getDeclContext()->getRedeclContext(); |
| 8395 | DeclContext *DC = S.CurContext->getRedeclContext(); |
| 8396 | |
| 8397 | // Make sure that this redeclaration (or definition) occurs in the same |
| 8398 | // scope or an enclosing namespace. |
| 8399 | if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext) |
| 8400 | : DC->Equals(SpecializedContext))) { |
| 8401 | if (isa<TranslationUnitDecl>(SpecializedContext)) |
| 8402 | S.Diag(Loc, diag::err_template_spec_redecl_global_scope) |
| 8403 | << EntityKind << Specialized; |
| 8404 | else { |
| 8405 | auto *ND = cast<NamedDecl>(SpecializedContext); |
| 8406 | int Diag = diag::err_template_spec_redecl_out_of_scope; |
| 8407 | if (S.getLangOpts().MicrosoftExt && !DC->isRecord()) |
| 8408 | Diag = diag::ext_ms_template_spec_redecl_out_of_scope; |
| 8409 | S.Diag(Loc, Diag) << EntityKind << Specialized |
| 8410 | << ND << isa<CXXRecordDecl>(ND); |
| 8411 | } |
| 8412 | |
| 8413 | S.Diag(Specialized->getLocation(), diag::note_specialized_entity); |
| 8414 | |
| 8415 | // Don't allow specializing in the wrong class during error recovery. |
| 8416 | // Otherwise, things can go horribly wrong. |
| 8417 | if (DC->isRecord()) |
| 8418 | return true; |
| 8419 | } |
| 8420 | |
| 8421 | return false; |
| 8422 | } |
| 8423 | |
| 8424 | static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) { |
| 8425 | if (!E->isTypeDependent()) |
| 8426 | return SourceLocation(); |
| 8427 | DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); |
| 8428 | Checker.TraverseStmt(E); |
| 8429 | if (Checker.MatchLoc.isInvalid()) |
| 8430 | return E->getSourceRange(); |
| 8431 | return Checker.MatchLoc; |
| 8432 | } |
| 8433 | |
| 8434 | static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) { |
| 8435 | if (!TL.getType()->isDependentType()) |
| 8436 | return SourceLocation(); |
| 8437 | DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); |
| 8438 | Checker.TraverseTypeLoc(TL); |
| 8439 | if (Checker.MatchLoc.isInvalid()) |
| 8440 | return TL.getSourceRange(); |
| 8441 | return Checker.MatchLoc; |
| 8442 | } |
| 8443 | |
| 8444 | /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs |
| 8445 | /// that checks non-type template partial specialization arguments. |
| 8446 | static bool CheckNonTypeTemplatePartialSpecializationArgs( |
| 8447 | Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, |
| 8448 | const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) { |
| 8449 | for (unsigned I = 0; I != NumArgs; ++I) { |
| 8450 | if (Args[I].getKind() == TemplateArgument::Pack) { |
| 8451 | if (CheckNonTypeTemplatePartialSpecializationArgs( |
| 8452 | S, TemplateNameLoc, Param, Args[I].pack_begin(), |
| 8453 | Args[I].pack_size(), IsDefaultArgument)) |
| 8454 | return true; |
| 8455 | |
| 8456 | continue; |
| 8457 | } |
| 8458 | |
| 8459 | if (Args[I].getKind() != TemplateArgument::Expression) |
| 8460 | continue; |
| 8461 | |
| 8462 | Expr *ArgExpr = Args[I].getAsExpr(); |
| 8463 | |
| 8464 | // We can have a pack expansion of any of the bullets below. |
| 8465 | if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr)) |
| 8466 | ArgExpr = Expansion->getPattern(); |
| 8467 | |
| 8468 | // Strip off any implicit casts we added as part of type checking. |
| 8469 | while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) |
| 8470 | ArgExpr = ICE->getSubExpr(); |
| 8471 | |
| 8472 | // C++ [temp.class.spec]p8: |
| 8473 | // A non-type argument is non-specialized if it is the name of a |
| 8474 | // non-type parameter. All other non-type arguments are |
| 8475 | // specialized. |
| 8476 | // |
| 8477 | // Below, we check the two conditions that only apply to |
| 8478 | // specialized non-type arguments, so skip any non-specialized |
| 8479 | // arguments. |
| 8480 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) |
| 8481 | if (isa<NonTypeTemplateParmDecl>(DRE->getDecl())) |
| 8482 | continue; |
| 8483 | |
| 8484 | // C++ [temp.class.spec]p9: |
| 8485 | // Within the argument list of a class template partial |
| 8486 | // specialization, the following restrictions apply: |
| 8487 | // -- A partially specialized non-type argument expression |
| 8488 | // shall not involve a template parameter of the partial |
| 8489 | // specialization except when the argument expression is a |
| 8490 | // simple identifier. |
| 8491 | // -- The type of a template parameter corresponding to a |
| 8492 | // specialized non-type argument shall not be dependent on a |
| 8493 | // parameter of the specialization. |
| 8494 | // DR1315 removes the first bullet, leaving an incoherent set of rules. |
| 8495 | // We implement a compromise between the original rules and DR1315: |
| 8496 | // -- A specialized non-type template argument shall not be |
| 8497 | // type-dependent and the corresponding template parameter |
| 8498 | // shall have a non-dependent type. |
| 8499 | SourceRange ParamUseRange = |
| 8500 | findTemplateParameterInType(Param->getDepth(), ArgExpr); |
| 8501 | if (ParamUseRange.isValid()) { |
| 8502 | if (IsDefaultArgument) { |
| 8503 | S.Diag(TemplateNameLoc, |
| 8504 | diag::err_dependent_non_type_arg_in_partial_spec); |
| 8505 | S.Diag(ParamUseRange.getBegin(), |
| 8506 | diag::note_dependent_non_type_default_arg_in_partial_spec) |
| 8507 | << ParamUseRange; |
| 8508 | } else { |
| 8509 | S.Diag(ParamUseRange.getBegin(), |
| 8510 | diag::err_dependent_non_type_arg_in_partial_spec) |
| 8511 | << ParamUseRange; |
| 8512 | } |
| 8513 | return true; |
| 8514 | } |
| 8515 | |
| 8516 | ParamUseRange = findTemplateParameter( |
| 8517 | Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc()); |
| 8518 | if (ParamUseRange.isValid()) { |
| 8519 | S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(), |
| 8520 | diag::err_dependent_typed_non_type_arg_in_partial_spec) |
| 8521 | << Param->getType(); |
| 8522 | S.Diag(Param->getLocation(), diag::note_template_param_here) |
| 8523 | << (IsDefaultArgument ? ParamUseRange : SourceRange()) |
| 8524 | << ParamUseRange; |
| 8525 | return true; |
| 8526 | } |
| 8527 | } |
| 8528 | |
| 8529 | return false; |
| 8530 | } |
| 8531 | |
| 8532 | /// Check the non-type template arguments of a class template |
| 8533 | /// partial specialization according to C++ [temp.class.spec]p9. |
| 8534 | /// |
| 8535 | /// \param TemplateNameLoc the location of the template name. |
| 8536 | /// \param PrimaryTemplate the template parameters of the primary class |
| 8537 | /// template. |
| 8538 | /// \param NumExplicit the number of explicitly-specified template arguments. |
| 8539 | /// \param TemplateArgs the template arguments of the class template |
| 8540 | /// partial specialization. |
| 8541 | /// |
| 8542 | /// \returns \c true if there was an error, \c false otherwise. |
| 8543 | bool Sema::CheckTemplatePartialSpecializationArgs( |
| 8544 | SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate, |
| 8545 | unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) { |
| 8546 | // We have to be conservative when checking a template in a dependent |
| 8547 | // context. |
| 8548 | if (PrimaryTemplate->getDeclContext()->isDependentContext()) |
| 8549 | return false; |
| 8550 | |
| 8551 | TemplateParameterList *TemplateParams = |
| 8552 | PrimaryTemplate->getTemplateParameters(); |
| 8553 | for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { |
| 8554 | NonTypeTemplateParmDecl *Param |
| 8555 | = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); |
| 8556 | if (!Param) |
| 8557 | continue; |
| 8558 | |
| 8559 | if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc, |
| 8560 | Param, &TemplateArgs[I], |
| 8561 | 1, I >= NumExplicit)) |
| 8562 | return true; |
| 8563 | } |
| 8564 | |
| 8565 | return false; |
| 8566 | } |
| 8567 | |
| 8568 | DeclResult Sema::ActOnClassTemplateSpecialization( |
| 8569 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
| 8570 | SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, |
| 8571 | TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, |
| 8572 | MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) { |
| 8573 | assert(TUK != TUK_Reference && "References are not specializations")(static_cast <bool> (TUK != TUK_Reference && "References are not specializations" ) ? void (0) : __assert_fail ("TUK != TUK_Reference && \"References are not specializations\"" , "clang/lib/Sema/SemaTemplate.cpp", 8573, __extension__ __PRETTY_FUNCTION__ )); |
| 8574 | |
| 8575 | // NOTE: KWLoc is the location of the tag keyword. This will instead |
| 8576 | // store the location of the outermost template keyword in the declaration. |
| 8577 | SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0 |
| 8578 | ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc; |
| 8579 | SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc; |
| 8580 | SourceLocation LAngleLoc = TemplateId.LAngleLoc; |
| 8581 | SourceLocation RAngleLoc = TemplateId.RAngleLoc; |
| 8582 | |
| 8583 | // Find the class template we're specializing |
| 8584 | TemplateName Name = TemplateId.Template.get(); |
| 8585 | ClassTemplateDecl *ClassTemplate |
| 8586 | = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); |
| 8587 | |
| 8588 | if (!ClassTemplate) { |
| 8589 | Diag(TemplateNameLoc, diag::err_not_class_template_specialization) |
| 8590 | << (Name.getAsTemplateDecl() && |
| 8591 | isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); |
| 8592 | return true; |
| 8593 | } |
| 8594 | |
| 8595 | bool isMemberSpecialization = false; |
| 8596 | bool isPartialSpecialization = false; |
| 8597 | |
| 8598 | // Check the validity of the template headers that introduce this |
| 8599 | // template. |
| 8600 | // FIXME: We probably shouldn't complain about these headers for |
| 8601 | // friend declarations. |
| 8602 | bool Invalid = false; |
| 8603 | TemplateParameterList *TemplateParams = |
| 8604 | MatchTemplateParametersToScopeSpecifier( |
| 8605 | KWLoc, TemplateNameLoc, SS, &TemplateId, |
| 8606 | TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization, |
| 8607 | Invalid); |
| 8608 | if (Invalid) |
| 8609 | return true; |
| 8610 | |
| 8611 | // Check that we can declare a template specialization here. |
| 8612 | if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams)) |
| 8613 | return true; |
| 8614 | |
| 8615 | if (TemplateParams && TemplateParams->size() > 0) { |
| 8616 | isPartialSpecialization = true; |
| 8617 | |
| 8618 | if (TUK == TUK_Friend) { |
| 8619 | Diag(KWLoc, diag::err_partial_specialization_friend) |
| 8620 | << SourceRange(LAngleLoc, RAngleLoc); |
| 8621 | return true; |
| 8622 | } |
| 8623 | |
| 8624 | // C++ [temp.class.spec]p10: |
| 8625 | // The template parameter list of a specialization shall not |
| 8626 | // contain default template argument values. |
| 8627 | for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { |
| 8628 | Decl *Param = TemplateParams->getParam(I); |
| 8629 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { |
| 8630 | if (TTP->hasDefaultArgument()) { |
| 8631 | Diag(TTP->getDefaultArgumentLoc(), |
| 8632 | diag::err_default_arg_in_partial_spec); |
| 8633 | TTP->removeDefaultArgument(); |
| 8634 | } |
| 8635 | } else if (NonTypeTemplateParmDecl *NTTP |
| 8636 | = dyn_cast<NonTypeTemplateParmDecl>(Param)) { |
| 8637 | if (Expr *DefArg = NTTP->getDefaultArgument()) { |
| 8638 | Diag(NTTP->getDefaultArgumentLoc(), |
| 8639 | diag::err_default_arg_in_partial_spec) |
| 8640 | << DefArg->getSourceRange(); |
| 8641 | NTTP->removeDefaultArgument(); |
| 8642 | } |
| 8643 | } else { |
| 8644 | TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); |
| 8645 | if (TTP->hasDefaultArgument()) { |
| 8646 | Diag(TTP->getDefaultArgument().getLocation(), |
| 8647 | diag::err_default_arg_in_partial_spec) |
| 8648 | << TTP->getDefaultArgument().getSourceRange(); |
| 8649 | TTP->removeDefaultArgument(); |
| 8650 | } |
| 8651 | } |
| 8652 | } |
| 8653 | } else if (TemplateParams) { |
| 8654 | if (TUK == TUK_Friend) |
| 8655 | Diag(KWLoc, diag::err_template_spec_friend) |
| 8656 | << FixItHint::CreateRemoval( |
| 8657 | SourceRange(TemplateParams->getTemplateLoc(), |
| 8658 | TemplateParams->getRAngleLoc())) |
| 8659 | << SourceRange(LAngleLoc, RAngleLoc); |
| 8660 | } else { |
| 8661 | assert(TUK == TUK_Friend && "should have a 'template<>' for this decl")(static_cast <bool> (TUK == TUK_Friend && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("TUK == TUK_Friend && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaTemplate.cpp", 8661, __extension__ __PRETTY_FUNCTION__ )); |
| 8662 | } |
| 8663 | |
| 8664 | // Check that the specialization uses the same tag kind as the |
| 8665 | // original template. |
| 8666 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
| 8667 | assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!")(static_cast <bool> (Kind != TTK_Enum && "Invalid enum tag in class template spec!" ) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template spec!\"" , "clang/lib/Sema/SemaTemplate.cpp", 8667, __extension__ __PRETTY_FUNCTION__ )); |
| 8668 | if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), |
| 8669 | Kind, TUK == TUK_Definition, KWLoc, |
| 8670 | ClassTemplate->getIdentifier())) { |
| 8671 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
| 8672 | << ClassTemplate |
| 8673 | << FixItHint::CreateReplacement(KWLoc, |
| 8674 | ClassTemplate->getTemplatedDecl()->getKindName()); |
| 8675 | Diag(ClassTemplate->getTemplatedDecl()->getLocation(), |
| 8676 | diag::note_previous_use); |
| 8677 | Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); |
| 8678 | } |
| 8679 | |
| 8680 | // Translate the parser's template argument list in our AST format. |
| 8681 | TemplateArgumentListInfo TemplateArgs = |
| 8682 | makeTemplateArgumentListInfo(*this, TemplateId); |
| 8683 | |
| 8684 | // Check for unexpanded parameter packs in any of the template arguments. |
| 8685 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
| 8686 | if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], |
| 8687 | UPPC_PartialSpecialization)) |
| 8688 | return true; |
| 8689 | |
| 8690 | // Check that the template argument list is well-formed for this |
| 8691 | // template. |
| 8692 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
| 8693 | if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, |
| 8694 | false, SugaredConverted, CanonicalConverted, |
| 8695 | /*UpdateArgsWithConversions=*/true)) |
| 8696 | return true; |
| 8697 | |
| 8698 | // Find the class template (partial) specialization declaration that |
| 8699 | // corresponds to these arguments. |
| 8700 | if (isPartialSpecialization) { |
| 8701 | if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate, |
| 8702 | TemplateArgs.size(), |
| 8703 | CanonicalConverted)) |
| 8704 | return true; |
| 8705 | |
| 8706 | // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we |
| 8707 | // also do it during instantiation. |
| 8708 | if (!Name.isDependent() && |
| 8709 | !TemplateSpecializationType::anyDependentTemplateArguments( |
| 8710 | TemplateArgs, CanonicalConverted)) { |
| 8711 | Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) |
| 8712 | << ClassTemplate->getDeclName(); |
| 8713 | isPartialSpecialization = false; |
| 8714 | } |
| 8715 | } |
| 8716 | |
| 8717 | void *InsertPos = nullptr; |
| 8718 | ClassTemplateSpecializationDecl *PrevDecl = nullptr; |
| 8719 | |
| 8720 | if (isPartialSpecialization) |
| 8721 | PrevDecl = ClassTemplate->findPartialSpecialization( |
| 8722 | CanonicalConverted, TemplateParams, InsertPos); |
| 8723 | else |
| 8724 | PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); |
| 8725 | |
| 8726 | ClassTemplateSpecializationDecl *Specialization = nullptr; |
| 8727 | |
| 8728 | // Check whether we can declare a class template specialization in |
| 8729 | // the current scope. |
| 8730 | if (TUK != TUK_Friend && |
| 8731 | CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, |
| 8732 | TemplateNameLoc, |
| 8733 | isPartialSpecialization)) |
| 8734 | return true; |
| 8735 | |
| 8736 | // The canonical type |
| 8737 | QualType CanonType; |
| 8738 | if (isPartialSpecialization) { |
| 8739 | // Build the canonical type that describes the converted template |
| 8740 | // arguments of the class template partial specialization. |
| 8741 | TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); |
| 8742 | CanonType = Context.getTemplateSpecializationType(CanonTemplate, |
| 8743 | CanonicalConverted); |
| 8744 | |
| 8745 | if (Context.hasSameType(CanonType, |
| 8746 | ClassTemplate->getInjectedClassNameSpecialization()) && |
| 8747 | (!Context.getLangOpts().CPlusPlus20 || |
| 8748 | !TemplateParams->hasAssociatedConstraints())) { |
| 8749 | // C++ [temp.class.spec]p9b3: |
| 8750 | // |
| 8751 | // -- The argument list of the specialization shall not be identical |
| 8752 | // to the implicit argument list of the primary template. |
| 8753 | // |
| 8754 | // This rule has since been removed, because it's redundant given DR1495, |
| 8755 | // but we keep it because it produces better diagnostics and recovery. |
| 8756 | Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) |
| 8757 | << /*class template*/0 << (TUK == TUK_Definition) |
| 8758 | << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); |
| 8759 | return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, |
| 8760 | ClassTemplate->getIdentifier(), |
| 8761 | TemplateNameLoc, |
| 8762 | Attr, |
| 8763 | TemplateParams, |
| 8764 | AS_none, /*ModulePrivateLoc=*/SourceLocation(), |
| 8765 | /*FriendLoc*/SourceLocation(), |
| 8766 | TemplateParameterLists.size() - 1, |
| 8767 | TemplateParameterLists.data()); |
| 8768 | } |
| 8769 | |
| 8770 | // Create a new class template partial specialization declaration node. |
| 8771 | ClassTemplatePartialSpecializationDecl *PrevPartial |
| 8772 | = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); |
| 8773 | ClassTemplatePartialSpecializationDecl *Partial = |
| 8774 | ClassTemplatePartialSpecializationDecl::Create( |
| 8775 | Context, Kind, ClassTemplate->getDeclContext(), KWLoc, |
| 8776 | TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted, |
| 8777 | TemplateArgs, CanonType, PrevPartial); |
| 8778 | SetNestedNameSpecifier(*this, Partial, SS); |
| 8779 | if (TemplateParameterLists.size() > 1 && SS.isSet()) { |
| 8780 | Partial->setTemplateParameterListsInfo( |
| 8781 | Context, TemplateParameterLists.drop_back(1)); |
| 8782 | } |
| 8783 | |
| 8784 | if (!PrevPartial) |
| 8785 | ClassTemplate->AddPartialSpecialization(Partial, InsertPos); |
| 8786 | Specialization = Partial; |
| 8787 | |
| 8788 | // If we are providing an explicit specialization of a member class |
| 8789 | // template specialization, make a note of that. |
| 8790 | if (PrevPartial && PrevPartial->getInstantiatedFromMember()) |
| 8791 | PrevPartial->setMemberSpecialization(); |
| 8792 | |
| 8793 | CheckTemplatePartialSpecialization(Partial); |
| 8794 | } else { |
| 8795 | // Create a new class template specialization declaration node for |
| 8796 | // this explicit specialization or friend declaration. |
| 8797 | Specialization = ClassTemplateSpecializationDecl::Create( |
| 8798 | Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc, |
| 8799 | ClassTemplate, CanonicalConverted, PrevDecl); |
| 8800 | SetNestedNameSpecifier(*this, Specialization, SS); |
| 8801 | if (TemplateParameterLists.size() > 0) { |
| 8802 | Specialization->setTemplateParameterListsInfo(Context, |
| 8803 | TemplateParameterLists); |
| 8804 | } |
| 8805 | |
| 8806 | if (!PrevDecl) |
| 8807 | ClassTemplate->AddSpecialization(Specialization, InsertPos); |
| 8808 | |
| 8809 | if (CurContext->isDependentContext()) { |
| 8810 | TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); |
| 8811 | CanonType = Context.getTemplateSpecializationType(CanonTemplate, |
| 8812 | CanonicalConverted); |
| 8813 | } else { |
| 8814 | CanonType = Context.getTypeDeclType(Specialization); |
| 8815 | } |
| 8816 | } |
| 8817 | |
| 8818 | // C++ [temp.expl.spec]p6: |
| 8819 | // If a template, a member template or the member of a class template is |
| 8820 | // explicitly specialized then that specialization shall be declared |
| 8821 | // before the first use of that specialization that would cause an implicit |
| 8822 | // instantiation to take place, in every translation unit in which such a |
| 8823 | // use occurs; no diagnostic is required. |
| 8824 | if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { |
| 8825 | bool Okay = false; |
| 8826 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
| 8827 | // Is there any previous explicit specialization declaration? |
| 8828 | if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { |
| 8829 | Okay = true; |
| 8830 | break; |
| 8831 | } |
| 8832 | } |
| 8833 | |
| 8834 | if (!Okay) { |
| 8835 | SourceRange Range(TemplateNameLoc, RAngleLoc); |
| 8836 | Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) |
| 8837 | << Context.getTypeDeclType(Specialization) << Range; |
| 8838 | |
| 8839 | Diag(PrevDecl->getPointOfInstantiation(), |
| 8840 | diag::note_instantiation_required_here) |
| 8841 | << (PrevDecl->getTemplateSpecializationKind() |
| 8842 | != TSK_ImplicitInstantiation); |
| 8843 | return true; |
| 8844 | } |
| 8845 | } |
| 8846 | |
| 8847 | // If this is not a friend, note that this is an explicit specialization. |
| 8848 | if (TUK != TUK_Friend) |
| 8849 | Specialization->setSpecializationKind(TSK_ExplicitSpecialization); |
| 8850 | |
| 8851 | // Check that this isn't a redefinition of this specialization. |
| 8852 | if (TUK == TUK_Definition) { |
| 8853 | RecordDecl *Def = Specialization->getDefinition(); |
| 8854 | NamedDecl *Hidden = nullptr; |
| 8855 | if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) { |
| 8856 | SkipBody->ShouldSkip = true; |
| 8857 | SkipBody->Previous = Def; |
| 8858 | makeMergedDefinitionVisible(Hidden); |
| 8859 | } else if (Def) { |
| 8860 | SourceRange Range(TemplateNameLoc, RAngleLoc); |
| 8861 | Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range; |
| 8862 | Diag(Def->getLocation(), diag::note_previous_definition); |
| 8863 | Specialization->setInvalidDecl(); |
| 8864 | return true; |
| 8865 | } |
| 8866 | } |
| 8867 | |
| 8868 | ProcessDeclAttributeList(S, Specialization, Attr); |
| 8869 | |
| 8870 | // Add alignment attributes if necessary; these attributes are checked when |
| 8871 | // the ASTContext lays out the structure. |
| 8872 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
| 8873 | AddAlignmentAttributesForRecord(Specialization); |
| 8874 | AddMsStructLayoutForRecord(Specialization); |
| 8875 | } |
| 8876 | |
| 8877 | if (ModulePrivateLoc.isValid()) |
| 8878 | Diag(Specialization->getLocation(), diag::err_module_private_specialization) |
| 8879 | << (isPartialSpecialization? 1 : 0) |
| 8880 | << FixItHint::CreateRemoval(ModulePrivateLoc); |
| 8881 | |
| 8882 | // Build the fully-sugared type for this class template |
| 8883 | // specialization as the user wrote in the specialization |
| 8884 | // itself. This means that we'll pretty-print the type retrieved |
| 8885 | // from the specialization's declaration the way that the user |
| 8886 | // actually wrote the specialization, rather than formatting the |
| 8887 | // name based on the "canonical" representation used to store the |
| 8888 | // template arguments in the specialization. |
| 8889 | TypeSourceInfo *WrittenTy |
| 8890 | = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, |
| 8891 | TemplateArgs, CanonType); |
| 8892 | if (TUK != TUK_Friend) { |
| 8893 | Specialization->setTypeAsWritten(WrittenTy); |
| 8894 | Specialization->setTemplateKeywordLoc(TemplateKWLoc); |
| 8895 | } |
| 8896 | |
| 8897 | // C++ [temp.expl.spec]p9: |
| 8898 | // A template explicit specialization is in the scope of the |
| 8899 | // namespace in which the template was defined. |
| 8900 | // |
| 8901 | // We actually implement this paragraph where we set the semantic |
| 8902 | // context (in the creation of the ClassTemplateSpecializationDecl), |
| 8903 | // but we also maintain the lexical context where the actual |
| 8904 | // definition occurs. |
| 8905 | Specialization->setLexicalDeclContext(CurContext); |
| 8906 | |
| 8907 | // We may be starting the definition of this specialization. |
| 8908 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) |
| 8909 | Specialization->startDefinition(); |
| 8910 | |
| 8911 | if (TUK == TUK_Friend) { |
| 8912 | FriendDecl *Friend = FriendDecl::Create(Context, CurContext, |
| 8913 | TemplateNameLoc, |
| 8914 | WrittenTy, |
| 8915 | /*FIXME:*/KWLoc); |
| 8916 | Friend->setAccess(AS_public); |
| 8917 | CurContext->addDecl(Friend); |
| 8918 | } else { |
| 8919 | // Add the specialization into its lexical context, so that it can |
| 8920 | // be seen when iterating through the list of declarations in that |
| 8921 | // context. However, specializations are not found by name lookup. |
| 8922 | CurContext->addDecl(Specialization); |
| 8923 | } |
| 8924 | |
| 8925 | if (SkipBody && SkipBody->ShouldSkip) |
| 8926 | return SkipBody->Previous; |
| 8927 | |
| 8928 | return Specialization; |
| 8929 | } |
| 8930 | |
| 8931 | Decl *Sema::ActOnTemplateDeclarator(Scope *S, |
| 8932 | MultiTemplateParamsArg TemplateParameterLists, |
| 8933 | Declarator &D) { |
| 8934 | Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists); |
| 8935 | ActOnDocumentableDecl(NewDecl); |
| 8936 | return NewDecl; |
| 8937 | } |
| 8938 | |
| 8939 | Decl *Sema::ActOnConceptDefinition(Scope *S, |
| 8940 | MultiTemplateParamsArg TemplateParameterLists, |
| 8941 | IdentifierInfo *Name, SourceLocation NameLoc, |
| 8942 | Expr *ConstraintExpr) { |
| 8943 | DeclContext *DC = CurContext; |
| 8944 | |
| 8945 | if (!DC->getRedeclContext()->isFileContext()) { |
| 8946 | Diag(NameLoc, |
| 8947 | diag::err_concept_decls_may_only_appear_in_global_namespace_scope); |
| 8948 | return nullptr; |
| 8949 | } |
| 8950 | |
| 8951 | if (TemplateParameterLists.size() > 1) { |
| 8952 | Diag(NameLoc, diag::err_concept_extra_headers); |
| 8953 | return nullptr; |
| 8954 | } |
| 8955 | |
| 8956 | TemplateParameterList *Params = TemplateParameterLists.front(); |
| 8957 | |
| 8958 | if (Params->size() == 0) { |
| 8959 | Diag(NameLoc, diag::err_concept_no_parameters); |
| 8960 | return nullptr; |
| 8961 | } |
| 8962 | |
| 8963 | // Ensure that the parameter pack, if present, is the last parameter in the |
| 8964 | // template. |
| 8965 | for (TemplateParameterList::const_iterator ParamIt = Params->begin(), |
| 8966 | ParamEnd = Params->end(); |
| 8967 | ParamIt != ParamEnd; ++ParamIt) { |
| 8968 | Decl const *Param = *ParamIt; |
| 8969 | if (Param->isParameterPack()) { |
| 8970 | if (++ParamIt == ParamEnd) |
| 8971 | break; |
| 8972 | Diag(Param->getLocation(), |
| 8973 | diag::err_template_param_pack_must_be_last_template_parameter); |
| 8974 | return nullptr; |
| 8975 | } |
| 8976 | } |
| 8977 | |
| 8978 | if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) |
| 8979 | return nullptr; |
| 8980 | |
| 8981 | ConceptDecl *NewDecl = |
| 8982 | ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr); |
| 8983 | |
| 8984 | if (NewDecl->hasAssociatedConstraints()) { |
| 8985 | // C++2a [temp.concept]p4: |
| 8986 | // A concept shall not have associated constraints. |
| 8987 | Diag(NameLoc, diag::err_concept_no_associated_constraints); |
| 8988 | NewDecl->setInvalidDecl(); |
| 8989 | } |
| 8990 | |
| 8991 | // Check for conflicting previous declaration. |
| 8992 | DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc); |
| 8993 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
| 8994 | forRedeclarationInCurContext()); |
| 8995 | LookupName(Previous, S); |
| 8996 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false, |
| 8997 | /*AllowInlineNamespace*/false); |
| 8998 | bool AddToScope = true; |
| 8999 | CheckConceptRedefinition(NewDecl, Previous, AddToScope); |
| 9000 | |
| 9001 | ActOnDocumentableDecl(NewDecl); |
| 9002 | if (AddToScope) |
| 9003 | PushOnScopeChains(NewDecl, S); |
| 9004 | return NewDecl; |
| 9005 | } |
| 9006 | |
| 9007 | void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl, |
| 9008 | LookupResult &Previous, bool &AddToScope) { |
| 9009 | AddToScope = true; |
| 9010 | |
| 9011 | if (Previous.empty()) |
| 9012 | return; |
| 9013 | |
| 9014 | auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl()); |
| 9015 | if (!OldConcept) { |
| 9016 | auto *Old = Previous.getRepresentativeDecl(); |
| 9017 | Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind) |
| 9018 | << NewDecl->getDeclName(); |
| 9019 | notePreviousDefinition(Old, NewDecl->getLocation()); |
| 9020 | AddToScope = false; |
| 9021 | return; |
| 9022 | } |
| 9023 | // Check if we can merge with a concept declaration. |
| 9024 | bool IsSame = Context.isSameEntity(NewDecl, OldConcept); |
| 9025 | if (!IsSame) { |
| 9026 | Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept) |
| 9027 | << NewDecl->getDeclName(); |
| 9028 | notePreviousDefinition(OldConcept, NewDecl->getLocation()); |
| 9029 | AddToScope = false; |
| 9030 | return; |
| 9031 | } |
| 9032 | if (hasReachableDefinition(OldConcept) && |
| 9033 | IsRedefinitionInModule(NewDecl, OldConcept)) { |
| 9034 | Diag(NewDecl->getLocation(), diag::err_redefinition) |
| 9035 | << NewDecl->getDeclName(); |
| 9036 | notePreviousDefinition(OldConcept, NewDecl->getLocation()); |
| 9037 | AddToScope = false; |
| 9038 | return; |
| 9039 | } |
| 9040 | if (!Previous.isSingleResult()) { |
| 9041 | // FIXME: we should produce an error in case of ambig and failed lookups. |
| 9042 | // Other decls (e.g. namespaces) also have this shortcoming. |
| 9043 | return; |
| 9044 | } |
| 9045 | // We unwrap canonical decl late to check for module visibility. |
| 9046 | Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl()); |
| 9047 | } |
| 9048 | |
| 9049 | /// \brief Strips various properties off an implicit instantiation |
| 9050 | /// that has just been explicitly specialized. |
| 9051 | static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) { |
| 9052 | if (MinGW || (isa<FunctionDecl>(D) && |
| 9053 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) { |
| 9054 | D->dropAttr<DLLImportAttr>(); |
| 9055 | D->dropAttr<DLLExportAttr>(); |
| 9056 | } |
| 9057 | |
| 9058 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) |
| 9059 | FD->setInlineSpecified(false); |
| 9060 | } |
| 9061 | |
| 9062 | /// Compute the diagnostic location for an explicit instantiation |
| 9063 | // declaration or definition. |
| 9064 | static SourceLocation DiagLocForExplicitInstantiation( |
| 9065 | NamedDecl* D, SourceLocation PointOfInstantiation) { |
| 9066 | // Explicit instantiations following a specialization have no effect and |
| 9067 | // hence no PointOfInstantiation. In that case, walk decl backwards |
| 9068 | // until a valid name loc is found. |
| 9069 | SourceLocation PrevDiagLoc = PointOfInstantiation; |
| 9070 | for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid(); |
| 9071 | Prev = Prev->getPreviousDecl()) { |
| 9072 | PrevDiagLoc = Prev->getLocation(); |
| 9073 | } |
| 9074 | assert(PrevDiagLoc.isValid() &&(static_cast <bool> (PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?" ) ? void (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\"" , "clang/lib/Sema/SemaTemplate.cpp", 9075, __extension__ __PRETTY_FUNCTION__ )) |
| 9075 | "Explicit instantiation without point of instantiation?")(static_cast <bool> (PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?" ) ? void (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\"" , "clang/lib/Sema/SemaTemplate.cpp", 9075, __extension__ __PRETTY_FUNCTION__ )); |
| 9076 | return PrevDiagLoc; |
| 9077 | } |
| 9078 | |
| 9079 | /// Diagnose cases where we have an explicit template specialization |
| 9080 | /// before/after an explicit template instantiation, producing diagnostics |
| 9081 | /// for those cases where they are required and determining whether the |
| 9082 | /// new specialization/instantiation will have any effect. |
| 9083 | /// |
| 9084 | /// \param NewLoc the location of the new explicit specialization or |
| 9085 | /// instantiation. |
| 9086 | /// |
| 9087 | /// \param NewTSK the kind of the new explicit specialization or instantiation. |
| 9088 | /// |
| 9089 | /// \param PrevDecl the previous declaration of the entity. |
| 9090 | /// |
| 9091 | /// \param PrevTSK the kind of the old explicit specialization or instantiatin. |
| 9092 | /// |
| 9093 | /// \param PrevPointOfInstantiation if valid, indicates where the previous |
| 9094 | /// declaration was instantiated (either implicitly or explicitly). |
| 9095 | /// |
| 9096 | /// \param HasNoEffect will be set to true to indicate that the new |
| 9097 | /// specialization or instantiation has no effect and should be ignored. |
| 9098 | /// |
| 9099 | /// \returns true if there was an error that should prevent the introduction of |
| 9100 | /// the new declaration into the AST, false otherwise. |
| 9101 | bool |
| 9102 | Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, |
| 9103 | TemplateSpecializationKind NewTSK, |
| 9104 | NamedDecl *PrevDecl, |
| 9105 | TemplateSpecializationKind PrevTSK, |
| 9106 | SourceLocation PrevPointOfInstantiation, |
| 9107 | bool &HasNoEffect) { |
| 9108 | HasNoEffect = false; |
| 9109 | |
| 9110 | switch (NewTSK) { |
| 9111 | case TSK_Undeclared: |
| 9112 | case TSK_ImplicitInstantiation: |
| 9113 | assert((static_cast <bool> ((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && "previous declaration must be implicit!" ) ? void (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\"" , "clang/lib/Sema/SemaTemplate.cpp", 9115, __extension__ __PRETTY_FUNCTION__ )) |
| 9114 | (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&(static_cast <bool> ((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && "previous declaration must be implicit!" ) ? void (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\"" , "clang/lib/Sema/SemaTemplate.cpp", 9115, __extension__ __PRETTY_FUNCTION__ )) |
| 9115 | "previous declaration must be implicit!")(static_cast <bool> ((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && "previous declaration must be implicit!" ) ? void (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\"" , "clang/lib/Sema/SemaTemplate.cpp", 9115, __extension__ __PRETTY_FUNCTION__ )); |
| 9116 | return false; |
| 9117 | |
| 9118 | case TSK_ExplicitSpecialization: |
| 9119 | switch (PrevTSK) { |
| 9120 | case TSK_Undeclared: |
| 9121 | case TSK_ExplicitSpecialization: |
| 9122 | // Okay, we're just specializing something that is either already |
| 9123 | // explicitly specialized or has merely been mentioned without any |
| 9124 | // instantiation. |
| 9125 | return false; |
| 9126 | |
| 9127 | case TSK_ImplicitInstantiation: |
| 9128 | if (PrevPointOfInstantiation.isInvalid()) { |
| 9129 | // The declaration itself has not actually been instantiated, so it is |
| 9130 | // still okay to specialize it. |
| 9131 | StripImplicitInstantiation( |
| 9132 | PrevDecl, |
| 9133 | Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()); |
| 9134 | return false; |
| 9135 | } |
| 9136 | // Fall through |
| 9137 | [[fallthrough]]; |
| 9138 | |
| 9139 | case TSK_ExplicitInstantiationDeclaration: |
| 9140 | case TSK_ExplicitInstantiationDefinition: |
| 9141 | assert((PrevTSK == TSK_ImplicitInstantiation ||(static_cast <bool> ((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && "Explicit instantiation without point of instantiation?" ) ? void (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\"" , "clang/lib/Sema/SemaTemplate.cpp", 9143, __extension__ __PRETTY_FUNCTION__ )) |
| 9142 | PrevPointOfInstantiation.isValid()) &&(static_cast <bool> ((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && "Explicit instantiation without point of instantiation?" ) ? void (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\"" , "clang/lib/Sema/SemaTemplate.cpp", 9143, __extension__ __PRETTY_FUNCTION__ )) |
| 9143 | "Explicit instantiation without point of instantiation?")(static_cast <bool> ((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && "Explicit instantiation without point of instantiation?" ) ? void (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\"" , "clang/lib/Sema/SemaTemplate.cpp", 9143, __extension__ __PRETTY_FUNCTION__ )); |
| 9144 | |
| 9145 | // C++ [temp.expl.spec]p6: |
| 9146 | // If a template, a member template or the member of a class template |
| 9147 | // is explicitly specialized then that specialization shall be declared |
| 9148 | // before the first use of that specialization that would cause an |
| 9149 | // implicit instantiation to take place, in every translation unit in |
| 9150 | // which such a use occurs; no diagnostic is required. |
| 9151 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
| 9152 | // Is there any previous explicit specialization declaration? |
| 9153 | if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) |
| 9154 | return false; |
| 9155 | } |
| 9156 | |
| 9157 | Diag(NewLoc, diag::err_specialization_after_instantiation) |
| 9158 | << PrevDecl; |
| 9159 | Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) |
| 9160 | << (PrevTSK != TSK_ImplicitInstantiation); |
| 9161 | |
| 9162 | return true; |
| 9163 | } |
| 9164 | llvm_unreachable("The switch over PrevTSK must be exhaustive.")::llvm::llvm_unreachable_internal("The switch over PrevTSK must be exhaustive." , "clang/lib/Sema/SemaTemplate.cpp", 9164); |
| 9165 | |
| 9166 | case TSK_ExplicitInstantiationDeclaration: |
| 9167 | switch (PrevTSK) { |
| 9168 | case TSK_ExplicitInstantiationDeclaration: |
| 9169 | // This explicit instantiation declaration is redundant (that's okay). |
| 9170 | HasNoEffect = true; |
| 9171 | return false; |
| 9172 | |
| 9173 | case TSK_Undeclared: |
| 9174 | case TSK_ImplicitInstantiation: |
| 9175 | // We're explicitly instantiating something that may have already been |
| 9176 | // implicitly instantiated; that's fine. |
| 9177 | return false; |
| 9178 | |
| 9179 | case TSK_ExplicitSpecialization: |
| 9180 | // C++0x [temp.explicit]p4: |
| 9181 | // For a given set of template parameters, if an explicit instantiation |
| 9182 | // of a template appears after a declaration of an explicit |
| 9183 | // specialization for that template, the explicit instantiation has no |
| 9184 | // effect. |
| 9185 | HasNoEffect = true; |
| 9186 | return false; |
| 9187 | |
| 9188 | case TSK_ExplicitInstantiationDefinition: |
| 9189 | // C++0x [temp.explicit]p10: |
| 9190 | // If an entity is the subject of both an explicit instantiation |
| 9191 | // declaration and an explicit instantiation definition in the same |
| 9192 | // translation unit, the definition shall follow the declaration. |
| 9193 | Diag(NewLoc, |
| 9194 | diag::err_explicit_instantiation_declaration_after_definition); |
| 9195 | |
| 9196 | // Explicit instantiations following a specialization have no effect and |
| 9197 | // hence no PrevPointOfInstantiation. In that case, walk decl backwards |
| 9198 | // until a valid name loc is found. |
| 9199 | Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), |
| 9200 | diag::note_explicit_instantiation_definition_here); |
| 9201 | HasNoEffect = true; |
| 9202 | return false; |
| 9203 | } |
| 9204 | llvm_unreachable("Unexpected TemplateSpecializationKind!")::llvm::llvm_unreachable_internal("Unexpected TemplateSpecializationKind!" , "clang/lib/Sema/SemaTemplate.cpp", 9204); |
| 9205 | |
| 9206 | case TSK_ExplicitInstantiationDefinition: |
| 9207 | switch (PrevTSK) { |
| 9208 | case TSK_Undeclared: |
| 9209 | case TSK_ImplicitInstantiation: |
| 9210 | // We're explicitly instantiating something that may have already been |
| 9211 | // implicitly instantiated; that's fine. |
| 9212 | return false; |
| 9213 | |
| 9214 | case TSK_ExplicitSpecialization: |
| 9215 | // C++ DR 259, C++0x [temp.explicit]p4: |
| 9216 | // For a given set of template parameters, if an explicit |
| 9217 | // instantiation of a template appears after a declaration of |
| 9218 | // an explicit specialization for that template, the explicit |
| 9219 | // instantiation has no effect. |
| 9220 | Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization) |
| 9221 | << PrevDecl; |
| 9222 | Diag(PrevDecl->getLocation(), |
| 9223 | diag::note_previous_template_specialization); |
| 9224 | HasNoEffect = true; |
| 9225 | return false; |
| 9226 | |
| 9227 | case TSK_ExplicitInstantiationDeclaration: |
| 9228 | // We're explicitly instantiating a definition for something for which we |
| 9229 | // were previously asked to suppress instantiations. That's fine. |
| 9230 | |
| 9231 | // C++0x [temp.explicit]p4: |
| 9232 | // For a given set of template parameters, if an explicit instantiation |
| 9233 | // of a template appears after a declaration of an explicit |
| 9234 | // specialization for that template, the explicit instantiation has no |
| 9235 | // effect. |
| 9236 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
| 9237 | // Is there any previous explicit specialization declaration? |
| 9238 | if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { |
| 9239 | HasNoEffect = true; |
| 9240 | break; |
| 9241 | } |
| 9242 | } |
| 9243 | |
| 9244 | return false; |
| 9245 | |
| 9246 | case TSK_ExplicitInstantiationDefinition: |
| 9247 | // C++0x [temp.spec]p5: |
| 9248 | // For a given template and a given set of template-arguments, |
| 9249 | // - an explicit instantiation definition shall appear at most once |
| 9250 | // in a program, |
| 9251 | |
| 9252 | // MSVCCompat: MSVC silently ignores duplicate explicit instantiations. |
| 9253 | Diag(NewLoc, (getLangOpts().MSVCCompat) |
| 9254 | ? diag::ext_explicit_instantiation_duplicate |
| 9255 | : diag::err_explicit_instantiation_duplicate) |
| 9256 | << PrevDecl; |
| 9257 | Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), |
| 9258 | diag::note_previous_explicit_instantiation); |
| 9259 | HasNoEffect = true; |
| 9260 | return false; |
| 9261 | } |
| 9262 | } |
| 9263 | |
| 9264 | llvm_unreachable("Missing specialization/instantiation case?")::llvm::llvm_unreachable_internal("Missing specialization/instantiation case?" , "clang/lib/Sema/SemaTemplate.cpp", 9264); |
| 9265 | } |
| 9266 | |
| 9267 | /// Perform semantic analysis for the given dependent function |
| 9268 | /// template specialization. |
| 9269 | /// |
| 9270 | /// The only possible way to get a dependent function template specialization |
| 9271 | /// is with a friend declaration, like so: |
| 9272 | /// |
| 9273 | /// \code |
| 9274 | /// template \<class T> void foo(T); |
| 9275 | /// template \<class T> class A { |
| 9276 | /// friend void foo<>(T); |
| 9277 | /// }; |
| 9278 | /// \endcode |
| 9279 | /// |
| 9280 | /// There really isn't any useful analysis we can do here, so we |
| 9281 | /// just store the information. |
| 9282 | bool |
| 9283 | Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, |
| 9284 | const TemplateArgumentListInfo &ExplicitTemplateArgs, |
| 9285 | LookupResult &Previous) { |
| 9286 | // Remove anything from Previous that isn't a function template in |
| 9287 | // the correct context. |
| 9288 | DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); |
| 9289 | LookupResult::Filter F = Previous.makeFilter(); |
| 9290 | enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing }; |
| 9291 | SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates; |
| 9292 | while (F.hasNext()) { |
| 9293 | NamedDecl *D = F.next()->getUnderlyingDecl(); |
| 9294 | if (!isa<FunctionTemplateDecl>(D)) { |
| 9295 | F.erase(); |
| 9296 | DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D)); |
| 9297 | continue; |
| 9298 | } |
| 9299 | |
| 9300 | if (!FDLookupContext->InEnclosingNamespaceSetOf( |
| 9301 | D->getDeclContext()->getRedeclContext())) { |
| 9302 | F.erase(); |
| 9303 | DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D)); |
| 9304 | continue; |
| 9305 | } |
| 9306 | } |
| 9307 | F.done(); |
| 9308 | |
| 9309 | if (Previous.empty()) { |
| 9310 | Diag(FD->getLocation(), |
| 9311 | diag::err_dependent_function_template_spec_no_match); |
| 9312 | for (auto &P : DiscardedCandidates) |
| 9313 | Diag(P.second->getLocation(), |
| 9314 | diag::note_dependent_function_template_spec_discard_reason) |
| 9315 | << P.first; |
| 9316 | return true; |
| 9317 | } |
| 9318 | |
| 9319 | FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(), |
| 9320 | ExplicitTemplateArgs); |
| 9321 | return false; |
| 9322 | } |
| 9323 | |
| 9324 | /// Perform semantic analysis for the given function template |
| 9325 | /// specialization. |
| 9326 | /// |
| 9327 | /// This routine performs all of the semantic analysis required for an |
| 9328 | /// explicit function template specialization. On successful completion, |
| 9329 | /// the function declaration \p FD will become a function template |
| 9330 | /// specialization. |
| 9331 | /// |
| 9332 | /// \param FD the function declaration, which will be updated to become a |
| 9333 | /// function template specialization. |
| 9334 | /// |
| 9335 | /// \param ExplicitTemplateArgs the explicitly-provided template arguments, |
| 9336 | /// if any. Note that this may be valid info even when 0 arguments are |
| 9337 | /// explicitly provided as in, e.g., \c void sort<>(char*, char*); |
| 9338 | /// as it anyway contains info on the angle brackets locations. |
| 9339 | /// |
| 9340 | /// \param Previous the set of declarations that may be specialized by |
| 9341 | /// this function specialization. |
| 9342 | /// |
| 9343 | /// \param QualifiedFriend whether this is a lookup for a qualified friend |
| 9344 | /// declaration with no explicit template argument list that might be |
| 9345 | /// befriending a function template specialization. |
| 9346 | bool Sema::CheckFunctionTemplateSpecialization( |
| 9347 | FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, |
| 9348 | LookupResult &Previous, bool QualifiedFriend) { |
| 9349 | // The set of function template specializations that could match this |
| 9350 | // explicit function template specialization. |
| 9351 | UnresolvedSet<8> Candidates; |
| 9352 | TemplateSpecCandidateSet FailedCandidates(FD->getLocation(), |
| 9353 | /*ForTakingAddress=*/false); |
| 9354 | |
| 9355 | llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8> |
| 9356 | ConvertedTemplateArgs; |
| 9357 | |
| 9358 | DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); |
| 9359 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
| 9360 | I != E; ++I) { |
| 9361 | NamedDecl *Ovl = (*I)->getUnderlyingDecl(); |
| 9362 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { |
| 9363 | // Only consider templates found within the same semantic lookup scope as |
| 9364 | // FD. |
| 9365 | if (!FDLookupContext->InEnclosingNamespaceSetOf( |
| 9366 | Ovl->getDeclContext()->getRedeclContext())) |
| 9367 | continue; |
| 9368 | |
| 9369 | // When matching a constexpr member function template specialization |
| 9370 | // against the primary template, we don't yet know whether the |
| 9371 | // specialization has an implicit 'const' (because we don't know whether |
| 9372 | // it will be a static member function until we know which template it |
| 9373 | // specializes), so adjust it now assuming it specializes this template. |
| 9374 | QualType FT = FD->getType(); |
| 9375 | if (FD->isConstexpr()) { |
| 9376 | CXXMethodDecl *OldMD = |
| 9377 | dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); |
| 9378 | if (OldMD && OldMD->isConst()) { |
| 9379 | const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>(); |
| 9380 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
| 9381 | EPI.TypeQuals.addConst(); |
| 9382 | FT = Context.getFunctionType(FPT->getReturnType(), |
| 9383 | FPT->getParamTypes(), EPI); |
| 9384 | } |
| 9385 | } |
| 9386 | |
| 9387 | TemplateArgumentListInfo Args; |
| 9388 | if (ExplicitTemplateArgs) |
| 9389 | Args = *ExplicitTemplateArgs; |
| 9390 | |
| 9391 | // C++ [temp.expl.spec]p11: |
| 9392 | // A trailing template-argument can be left unspecified in the |
| 9393 | // template-id naming an explicit function template specialization |
| 9394 | // provided it can be deduced from the function argument type. |
| 9395 | // Perform template argument deduction to determine whether we may be |
| 9396 | // specializing this template. |
| 9397 | // FIXME: It is somewhat wasteful to build |
| 9398 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
| 9399 | FunctionDecl *Specialization = nullptr; |
| 9400 | if (TemplateDeductionResult TDK = DeduceTemplateArguments( |
| 9401 | cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()), |
| 9402 | ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, |
| 9403 | Info)) { |
| 9404 | // Template argument deduction failed; record why it failed, so |
| 9405 | // that we can provide nifty diagnostics. |
| 9406 | FailedCandidates.addCandidate().set( |
| 9407 | I.getPair(), FunTmpl->getTemplatedDecl(), |
| 9408 | MakeDeductionFailureInfo(Context, TDK, Info)); |
| 9409 | (void)TDK; |
| 9410 | continue; |
| 9411 | } |
| 9412 | |
| 9413 | // Target attributes are part of the cuda function signature, so |
| 9414 | // the deduced template's cuda target must match that of the |
| 9415 | // specialization. Given that C++ template deduction does not |
| 9416 | // take target attributes into account, we reject candidates |
| 9417 | // here that have a different target. |
| 9418 | if (LangOpts.CUDA && |
| 9419 | IdentifyCUDATarget(Specialization, |
| 9420 | /* IgnoreImplicitHDAttr = */ true) != |
| 9421 | IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) { |
| 9422 | FailedCandidates.addCandidate().set( |
| 9423 | I.getPair(), FunTmpl->getTemplatedDecl(), |
| 9424 | MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); |
| 9425 | continue; |
| 9426 | } |
| 9427 | |
| 9428 | // Record this candidate. |
| 9429 | if (ExplicitTemplateArgs) |
| 9430 | ConvertedTemplateArgs[Specialization] = std::move(Args); |
| 9431 | Candidates.addDecl(Specialization, I.getAccess()); |
| 9432 | } |
| 9433 | } |
| 9434 | |
| 9435 | // For a qualified friend declaration (with no explicit marker to indicate |
| 9436 | // that a template specialization was intended), note all (template and |
| 9437 | // non-template) candidates. |
| 9438 | if (QualifiedFriend && Candidates.empty()) { |
| 9439 | Diag(FD->getLocation(), diag::err_qualified_friend_no_match) |
| 9440 | << FD->getDeclName() << FDLookupContext; |
| 9441 | // FIXME: We should form a single candidate list and diagnose all |
| 9442 | // candidates at once, to get proper sorting and limiting. |
| 9443 | for (auto *OldND : Previous) { |
| 9444 | if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl())) |
| 9445 | NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false); |
| 9446 | } |
| 9447 | FailedCandidates.NoteCandidates(*this, FD->getLocation()); |
| 9448 | return true; |
| 9449 | } |
| 9450 | |
| 9451 | // Find the most specialized function template. |
| 9452 | UnresolvedSetIterator Result = getMostSpecialized( |
| 9453 | Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(), |
| 9454 | PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(), |
| 9455 | PDiag(diag::err_function_template_spec_ambiguous) |
| 9456 | << FD->getDeclName() << (ExplicitTemplateArgs != nullptr), |
| 9457 | PDiag(diag::note_function_template_spec_matched)); |
| 9458 | |
| 9459 | if (Result == Candidates.end()) |
| 9460 | return true; |
| 9461 | |
| 9462 | // Ignore access information; it doesn't figure into redeclaration checking. |
| 9463 | FunctionDecl *Specialization = cast<FunctionDecl>(*Result); |
| 9464 | |
| 9465 | FunctionTemplateSpecializationInfo *SpecInfo |
| 9466 | = Specialization->getTemplateSpecializationInfo(); |
| 9467 | assert(SpecInfo && "Function template specialization info missing?")(static_cast <bool> (SpecInfo && "Function template specialization info missing?" ) ? void (0) : __assert_fail ("SpecInfo && \"Function template specialization info missing?\"" , "clang/lib/Sema/SemaTemplate.cpp", 9467, __extension__ __PRETTY_FUNCTION__ )); |
| 9468 | |
| 9469 | // Note: do not overwrite location info if previous template |
| 9470 | // specialization kind was explicit. |
| 9471 | TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind(); |
| 9472 | if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) { |
| 9473 | Specialization->setLocation(FD->getLocation()); |
| 9474 | Specialization->setLexicalDeclContext(FD->getLexicalDeclContext()); |
| 9475 | // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr |
| 9476 | // function can differ from the template declaration with respect to |
| 9477 | // the constexpr specifier. |
| 9478 | // FIXME: We need an update record for this AST mutation. |
| 9479 | // FIXME: What if there are multiple such prior declarations (for instance, |
| 9480 | // from different modules)? |
| 9481 | Specialization->setConstexprKind(FD->getConstexprKind()); |
| 9482 | } |
| 9483 | |
| 9484 | // FIXME: Check if the prior specialization has a point of instantiation. |
| 9485 | // If so, we have run afoul of . |
| 9486 | |
| 9487 | // If this is a friend declaration, then we're not really declaring |
| 9488 | // an explicit specialization. |
| 9489 | bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); |
| 9490 | |
| 9491 | // Check the scope of this explicit specialization. |
| 9492 | if (!isFriend && |
| 9493 | CheckTemplateSpecializationScope(*this, |
| 9494 | Specialization->getPrimaryTemplate(), |
| 9495 | Specialization, FD->getLocation(), |
| 9496 | false)) |
| 9497 | return true; |
| 9498 | |
| 9499 | // C++ [temp.expl.spec]p6: |
| 9500 | // If a template, a member template or the member of a class template is |
| 9501 | // explicitly specialized then that specialization shall be declared |
| 9502 | // before the first use of that specialization that would cause an implicit |
| 9503 | // instantiation to take place, in every translation unit in which such a |
| 9504 | // use occurs; no diagnostic is required. |
| 9505 | bool HasNoEffect = false; |
| 9506 | if (!isFriend && |
| 9507 | CheckSpecializationInstantiationRedecl(FD->getLocation(), |
| 9508 | TSK_ExplicitSpecialization, |
| 9509 | Specialization, |
| 9510 | SpecInfo->getTemplateSpecializationKind(), |
| 9511 | SpecInfo->getPointOfInstantiation(), |
| 9512 | HasNoEffect)) |
| 9513 | return true; |
| 9514 | |
| 9515 | // Mark the prior declaration as an explicit specialization, so that later |
| 9516 | // clients know that this is an explicit specialization. |
| 9517 | if (!isFriend) { |
| 9518 | // Since explicit specializations do not inherit '=delete' from their |
| 9519 | // primary function template - check if the 'specialization' that was |
| 9520 | // implicitly generated (during template argument deduction for partial |
| 9521 | // ordering) from the most specialized of all the function templates that |
| 9522 | // 'FD' could have been specializing, has a 'deleted' definition. If so, |
| 9523 | // first check that it was implicitly generated during template argument |
| 9524 | // deduction by making sure it wasn't referenced, and then reset the deleted |
| 9525 | // flag to not-deleted, so that we can inherit that information from 'FD'. |
| 9526 | if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() && |
| 9527 | !Specialization->getCanonicalDecl()->isReferenced()) { |
| 9528 | // FIXME: This assert will not hold in the presence of modules. |
| 9529 | assert((static_cast <bool> (Specialization->getCanonicalDecl () == Specialization && "This must be the only existing declaration of this specialization" ) ? void (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\"" , "clang/lib/Sema/SemaTemplate.cpp", 9531, __extension__ __PRETTY_FUNCTION__ )) |
| 9530 | Specialization->getCanonicalDecl() == Specialization &&(static_cast <bool> (Specialization->getCanonicalDecl () == Specialization && "This must be the only existing declaration of this specialization" ) ? void (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\"" , "clang/lib/Sema/SemaTemplate.cpp", 9531, __extension__ __PRETTY_FUNCTION__ )) |
| 9531 | "This must be the only existing declaration of this specialization")(static_cast <bool> (Specialization->getCanonicalDecl () == Specialization && "This must be the only existing declaration of this specialization" ) ? void (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\"" , "clang/lib/Sema/SemaTemplate.cpp", 9531, __extension__ __PRETTY_FUNCTION__ )); |
| 9532 | // FIXME: We need an update record for this AST mutation. |
| 9533 | Specialization->setDeletedAsWritten(false); |
| 9534 | } |
| 9535 | // FIXME: We need an update record for this AST mutation. |
| 9536 | SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); |
| 9537 | MarkUnusedFileScopedDecl(Specialization); |
| 9538 | } |
| 9539 | |
| 9540 | // Turn the given function declaration into a function template |
| 9541 | // specialization, with the template arguments from the previous |
| 9542 | // specialization. |
| 9543 | // Take copies of (semantic and syntactic) template argument lists. |
| 9544 | const TemplateArgumentList* TemplArgs = new (Context) |
| 9545 | TemplateArgumentList(Specialization->getTemplateSpecializationArgs()); |
| 9546 | FD->setFunctionTemplateSpecialization( |
| 9547 | Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr, |
| 9548 | SpecInfo->getTemplateSpecializationKind(), |
| 9549 | ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr); |
| 9550 | |
| 9551 | // A function template specialization inherits the target attributes |
| 9552 | // of its template. (We require the attributes explicitly in the |
| 9553 | // code to match, but a template may have implicit attributes by |
| 9554 | // virtue e.g. of being constexpr, and it passes these implicit |
| 9555 | // attributes on to its specializations.) |
| 9556 | if (LangOpts.CUDA) |
| 9557 | inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate()); |
| 9558 | |
| 9559 | // The "previous declaration" for this function template specialization is |
| 9560 | // the prior function template specialization. |
| 9561 | Previous.clear(); |
| 9562 | Previous.addDecl(Specialization); |
| 9563 | return false; |
| 9564 | } |
| 9565 | |
| 9566 | /// Perform semantic analysis for the given non-template member |
| 9567 | /// specialization. |
| 9568 | /// |
| 9569 | /// This routine performs all of the semantic analysis required for an |
| 9570 | /// explicit member function specialization. On successful completion, |
| 9571 | /// the function declaration \p FD will become a member function |
| 9572 | /// specialization. |
| 9573 | /// |
| 9574 | /// \param Member the member declaration, which will be updated to become a |
| 9575 | /// specialization. |
| 9576 | /// |
| 9577 | /// \param Previous the set of declarations, one of which may be specialized |
| 9578 | /// by this function specialization; the set will be modified to contain the |
| 9579 | /// redeclared member. |
| 9580 | bool |
| 9581 | Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { |
| 9582 | assert(!isa<TemplateDecl>(Member) && "Only for non-template members")(static_cast <bool> (!isa<TemplateDecl>(Member) && "Only for non-template members") ? void (0) : __assert_fail ( "!isa<TemplateDecl>(Member) && \"Only for non-template members\"" , "clang/lib/Sema/SemaTemplate.cpp", 9582, __extension__ __PRETTY_FUNCTION__ )); |
| 9583 | |
| 9584 | // Try to find the member we are instantiating. |
| 9585 | NamedDecl *FoundInstantiation = nullptr; |
| 9586 | NamedDecl *Instantiation = nullptr; |
| 9587 | NamedDecl *InstantiatedFrom = nullptr; |
| 9588 | MemberSpecializationInfo *MSInfo = nullptr; |
| 9589 | |
| 9590 | if (Previous.empty()) { |
| 9591 | // Nowhere to look anyway. |
| 9592 | } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { |
| 9593 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
| 9594 | I != E; ++I) { |
| 9595 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
| 9596 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { |
| 9597 | QualType Adjusted = Function->getType(); |
| 9598 | if (!hasExplicitCallingConv(Adjusted)) |
| 9599 | Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType()); |
| 9600 | // This doesn't handle deduced return types, but both function |
| 9601 | // declarations should be undeduced at this point. |
| 9602 | if (Context.hasSameType(Adjusted, Method->getType())) { |
| 9603 | FoundInstantiation = *I; |
| 9604 | Instantiation = Method; |
| 9605 | InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); |
| 9606 | MSInfo = Method->getMemberSpecializationInfo(); |
| 9607 | break; |
| 9608 | } |
| 9609 | } |
| 9610 | } |
| 9611 | } else if (isa<VarDecl>(Member)) { |
| 9612 | VarDecl *PrevVar; |
| 9613 | if (Previous.isSingleResult() && |
| 9614 | (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) |
| 9615 | if (PrevVar->isStaticDataMember()) { |
| 9616 | FoundInstantiation = Previous.getRepresentativeDecl(); |
| 9617 | Instantiation = PrevVar; |
| 9618 | InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); |
| 9619 | MSInfo = PrevVar->getMemberSpecializationInfo(); |
| 9620 | } |
| 9621 | } else if (isa<RecordDecl>(Member)) { |
| 9622 | CXXRecordDecl *PrevRecord; |
| 9623 | if (Previous.isSingleResult() && |
| 9624 | (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { |
| 9625 | FoundInstantiation = Previous.getRepresentativeDecl(); |
| 9626 | Instantiation = PrevRecord; |
| 9627 | InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); |
| 9628 | MSInfo = PrevRecord->getMemberSpecializationInfo(); |
| 9629 | } |
| 9630 | } else if (isa<EnumDecl>(Member)) { |
| 9631 | EnumDecl *PrevEnum; |
| 9632 | if (Previous.isSingleResult() && |
| 9633 | (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) { |
| 9634 | FoundInstantiation = Previous.getRepresentativeDecl(); |
| 9635 | Instantiation = PrevEnum; |
| 9636 | InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum(); |
| 9637 | MSInfo = PrevEnum->getMemberSpecializationInfo(); |
| 9638 | } |
| 9639 | } |
| 9640 | |
| 9641 | if (!Instantiation) { |
| 9642 | // There is no previous declaration that matches. Since member |
| 9643 | // specializations are always out-of-line, the caller will complain about |
| 9644 | // this mismatch later. |
| 9645 | return false; |
| 9646 | } |
| 9647 | |
| 9648 | // A member specialization in a friend declaration isn't really declaring |
| 9649 | // an explicit specialization, just identifying a specific (possibly implicit) |
| 9650 | // specialization. Don't change the template specialization kind. |
| 9651 | // |
| 9652 | // FIXME: Is this really valid? Other compilers reject. |
| 9653 | if (Member->getFriendObjectKind() != Decl::FOK_None) { |
| 9654 | // Preserve instantiation information. |
| 9655 | if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { |
| 9656 | cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction( |
| 9657 | cast<CXXMethodDecl>(InstantiatedFrom), |
| 9658 | cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind()); |
| 9659 | } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) { |
| 9660 | cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( |
| 9661 | cast<CXXRecordDecl>(InstantiatedFrom), |
| 9662 | cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind()); |
| 9663 | } |
| 9664 | |
| 9665 | Previous.clear(); |
| 9666 | Previous.addDecl(FoundInstantiation); |
| 9667 | return false; |
| 9668 | } |
| 9669 | |
| 9670 | // Make sure that this is a specialization of a member. |
| 9671 | if (!InstantiatedFrom) { |
| 9672 | Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) |
| 9673 | << Member; |
| 9674 | Diag(Instantiation->getLocation(), diag::note_specialized_decl); |
| 9675 | return true; |
| 9676 | } |
| 9677 | |
| 9678 | // C++ [temp.expl.spec]p6: |
| 9679 | // If a template, a member template or the member of a class template is |
| 9680 | // explicitly specialized then that specialization shall be declared |
| 9681 | // before the first use of that specialization that would cause an implicit |
| 9682 | // instantiation to take place, in every translation unit in which such a |
| 9683 | // use occurs; no diagnostic is required. |
| 9684 | assert(MSInfo && "Member specialization info missing?")(static_cast <bool> (MSInfo && "Member specialization info missing?" ) ? void (0) : __assert_fail ("MSInfo && \"Member specialization info missing?\"" , "clang/lib/Sema/SemaTemplate.cpp", 9684, __extension__ __PRETTY_FUNCTION__ )); |
| 9685 | |
| 9686 | bool HasNoEffect = false; |
| 9687 | if (CheckSpecializationInstantiationRedecl(Member->getLocation(), |
| 9688 | TSK_ExplicitSpecialization, |
| 9689 | Instantiation, |
| 9690 | MSInfo->getTemplateSpecializationKind(), |
| 9691 | MSInfo->getPointOfInstantiation(), |
| 9692 | HasNoEffect)) |
| 9693 | return true; |
| 9694 | |
| 9695 | // Check the scope of this explicit specialization. |
| 9696 | if (CheckTemplateSpecializationScope(*this, |
| 9697 | InstantiatedFrom, |
| 9698 | Instantiation, Member->getLocation(), |
| 9699 | false)) |
| 9700 | return true; |
| 9701 | |
| 9702 | // Note that this member specialization is an "instantiation of" the |
| 9703 | // corresponding member of the original template. |
| 9704 | if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) { |
| 9705 | FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); |
| 9706 | if (InstantiationFunction->getTemplateSpecializationKind() == |
| 9707 | TSK_ImplicitInstantiation) { |
| 9708 | // Explicit specializations of member functions of class templates do not |
| 9709 | // inherit '=delete' from the member function they are specializing. |
| 9710 | if (InstantiationFunction->isDeleted()) { |
| 9711 | // FIXME: This assert will not hold in the presence of modules. |
| 9712 | assert(InstantiationFunction->getCanonicalDecl() ==(static_cast <bool> (InstantiationFunction->getCanonicalDecl () == InstantiationFunction) ? void (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction" , "clang/lib/Sema/SemaTemplate.cpp", 9713, __extension__ __PRETTY_FUNCTION__ )) |
| 9713 | InstantiationFunction)(static_cast <bool> (InstantiationFunction->getCanonicalDecl () == InstantiationFunction) ? void (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction" , "clang/lib/Sema/SemaTemplate.cpp", 9713, __extension__ __PRETTY_FUNCTION__ )); |
| 9714 | // FIXME: We need an update record for this AST mutation. |
| 9715 | InstantiationFunction->setDeletedAsWritten(false); |
| 9716 | } |
| 9717 | } |
| 9718 | |
| 9719 | MemberFunction->setInstantiationOfMemberFunction( |
| 9720 | cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); |
| 9721 | } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) { |
| 9722 | MemberVar->setInstantiationOfStaticDataMember( |
| 9723 | cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); |
| 9724 | } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) { |
| 9725 | MemberClass->setInstantiationOfMemberClass( |
| 9726 | cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); |
| 9727 | } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) { |
| 9728 | MemberEnum->setInstantiationOfMemberEnum( |
| 9729 | cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); |
| 9730 | } else { |
| 9731 | llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind" , "clang/lib/Sema/SemaTemplate.cpp", 9731); |
| 9732 | } |
| 9733 | |
| 9734 | // Save the caller the trouble of having to figure out which declaration |
| 9735 | // this specialization matches. |
| 9736 | Previous.clear(); |
| 9737 | Previous.addDecl(FoundInstantiation); |
| 9738 | return false; |
| 9739 | } |
| 9740 | |
| 9741 | /// Complete the explicit specialization of a member of a class template by |
| 9742 | /// updating the instantiated member to be marked as an explicit specialization. |
| 9743 | /// |
| 9744 | /// \param OrigD The member declaration instantiated from the template. |
| 9745 | /// \param Loc The location of the explicit specialization of the member. |
| 9746 | template<typename DeclT> |
| 9747 | static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, |
| 9748 | SourceLocation Loc) { |
| 9749 | if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) |
| 9750 | return; |
| 9751 | |
| 9752 | // FIXME: Inform AST mutation listeners of this AST mutation. |
| 9753 | // FIXME: If there are multiple in-class declarations of the member (from |
| 9754 | // multiple modules, or a declaration and later definition of a member type), |
| 9755 | // should we update all of them? |
| 9756 | OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization); |
| 9757 | OrigD->setLocation(Loc); |
| 9758 | } |
| 9759 | |
| 9760 | void Sema::CompleteMemberSpecialization(NamedDecl *Member, |
| 9761 | LookupResult &Previous) { |
| 9762 | NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl()); |
| 9763 | if (Instantiation == Member) |
| 9764 | return; |
| 9765 | |
| 9766 | if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation)) |
| 9767 | completeMemberSpecializationImpl(*this, Function, Member->getLocation()); |
| 9768 | else if (auto *Var = dyn_cast<VarDecl>(Instantiation)) |
| 9769 | completeMemberSpecializationImpl(*this, Var, Member->getLocation()); |
| 9770 | else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation)) |
| 9771 | completeMemberSpecializationImpl(*this, Record, Member->getLocation()); |
| 9772 | else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation)) |
| 9773 | completeMemberSpecializationImpl(*this, Enum, Member->getLocation()); |
| 9774 | else |
| 9775 | llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind" , "clang/lib/Sema/SemaTemplate.cpp", 9775); |
| 9776 | } |
| 9777 | |
| 9778 | /// Check the scope of an explicit instantiation. |
| 9779 | /// |
| 9780 | /// \returns true if a serious error occurs, false otherwise. |
| 9781 | static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, |
| 9782 | SourceLocation InstLoc, |
| 9783 | bool WasQualifiedName) { |
| 9784 | DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); |
| 9785 | DeclContext *CurContext = S.CurContext->getRedeclContext(); |
| 9786 | |
| 9787 | if (CurContext->isRecord()) { |
| 9788 | S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) |
| 9789 | << D; |
| 9790 | return true; |
| 9791 | } |
| 9792 | |
| 9793 | // C++11 [temp.explicit]p3: |
| 9794 | // An explicit instantiation shall appear in an enclosing namespace of its |
| 9795 | // template. If the name declared in the explicit instantiation is an |
| 9796 | // unqualified name, the explicit instantiation shall appear in the |
| 9797 | // namespace where its template is declared or, if that namespace is inline |
| 9798 | // (7.3.1), any namespace from its enclosing namespace set. |
| 9799 | // |
| 9800 | // This is DR275, which we do not retroactively apply to C++98/03. |
| 9801 | if (WasQualifiedName) { |
| 9802 | if (CurContext->Encloses(OrigContext)) |
| 9803 | return false; |
| 9804 | } else { |
| 9805 | if (CurContext->InEnclosingNamespaceSetOf(OrigContext)) |
| 9806 | return false; |
| 9807 | } |
| 9808 | |
| 9809 | if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) { |
| 9810 | if (WasQualifiedName) |
| 9811 | S.Diag(InstLoc, |
| 9812 | S.getLangOpts().CPlusPlus11? |
| 9813 | diag::err_explicit_instantiation_out_of_scope : |
| 9814 | diag::warn_explicit_instantiation_out_of_scope_0x) |
| 9815 | << D << NS; |
| 9816 | else |
| 9817 | S.Diag(InstLoc, |
| 9818 | S.getLangOpts().CPlusPlus11? |
| 9819 | diag::err_explicit_instantiation_unqualified_wrong_namespace : |
| 9820 | diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) |
| 9821 | << D << NS; |
| 9822 | } else |
| 9823 | S.Diag(InstLoc, |
| 9824 | S.getLangOpts().CPlusPlus11? |
| 9825 | diag::err_explicit_instantiation_must_be_global : |
| 9826 | diag::warn_explicit_instantiation_must_be_global_0x) |
| 9827 | << D; |
| 9828 | S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); |
| 9829 | return false; |
| 9830 | } |
| 9831 | |
| 9832 | /// Common checks for whether an explicit instantiation of \p D is valid. |
| 9833 | static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, |
| 9834 | SourceLocation InstLoc, |
| 9835 | bool WasQualifiedName, |
| 9836 | TemplateSpecializationKind TSK) { |
| 9837 | // C++ [temp.explicit]p13: |
| 9838 | // An explicit instantiation declaration shall not name a specialization of |
| 9839 | // a template with internal linkage. |
| 9840 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
| 9841 | D->getFormalLinkage() == InternalLinkage) { |
| 9842 | S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D; |
| 9843 | return true; |
| 9844 | } |
| 9845 | |
| 9846 | // C++11 [temp.explicit]p3: [DR 275] |
| 9847 | // An explicit instantiation shall appear in an enclosing namespace of its |
| 9848 | // template. |
| 9849 | if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName)) |
| 9850 | return true; |
| 9851 | |
| 9852 | return false; |
| 9853 | } |
| 9854 | |
| 9855 | /// Determine whether the given scope specifier has a template-id in it. |
| 9856 | static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { |
| 9857 | if (!SS.isSet()) |
| 9858 | return false; |
| 9859 | |
| 9860 | // C++11 [temp.explicit]p3: |
| 9861 | // If the explicit instantiation is for a member function, a member class |
| 9862 | // or a static data member of a class template specialization, the name of |
| 9863 | // the class template specialization in the qualified-id for the member |
| 9864 | // name shall be a simple-template-id. |
| 9865 | // |
| 9866 | // C++98 has the same restriction, just worded differently. |
| 9867 | for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS; |
| 9868 | NNS = NNS->getPrefix()) |
| 9869 | if (const Type *T = NNS->getAsType()) |
| 9870 | if (isa<TemplateSpecializationType>(T)) |
| 9871 | return true; |
| 9872 | |
| 9873 | return false; |
| 9874 | } |
| 9875 | |
| 9876 | /// Make a dllexport or dllimport attr on a class template specialization take |
| 9877 | /// effect. |
| 9878 | static void dllExportImportClassTemplateSpecialization( |
| 9879 | Sema &S, ClassTemplateSpecializationDecl *Def) { |
| 9880 | auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def)); |
| 9881 | assert(A && "dllExportImportClassTemplateSpecialization called "(static_cast <bool> (A && "dllExportImportClassTemplateSpecialization called " "on Def without dllexport or dllimport") ? void (0) : __assert_fail ("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\"" , "clang/lib/Sema/SemaTemplate.cpp", 9882, __extension__ __PRETTY_FUNCTION__ )) |
| 9882 | "on Def without dllexport or dllimport")(static_cast <bool> (A && "dllExportImportClassTemplateSpecialization called " "on Def without dllexport or dllimport") ? void (0) : __assert_fail ("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\"" , "clang/lib/Sema/SemaTemplate.cpp", 9882, __extension__ __PRETTY_FUNCTION__ )); |
| 9883 | |
| 9884 | // We reject explicit instantiations in class scope, so there should |
| 9885 | // never be any delayed exported classes to worry about. |
| 9886 | assert(S.DelayedDllExportClasses.empty() &&(static_cast <bool> (S.DelayedDllExportClasses.empty() && "delayed exports present at explicit instantiation") ? void ( 0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\"" , "clang/lib/Sema/SemaTemplate.cpp", 9887, __extension__ __PRETTY_FUNCTION__ )) |
| 9887 | "delayed exports present at explicit instantiation")(static_cast <bool> (S.DelayedDllExportClasses.empty() && "delayed exports present at explicit instantiation") ? void ( 0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\"" , "clang/lib/Sema/SemaTemplate.cpp", 9887, __extension__ __PRETTY_FUNCTION__ )); |
| 9888 | S.checkClassLevelDLLAttribute(Def); |
| 9889 | |
| 9890 | // Propagate attribute to base class templates. |
| 9891 | for (auto &B : Def->bases()) { |
| 9892 | if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>( |
| 9893 | B.getType()->getAsCXXRecordDecl())) |
| 9894 | S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc()); |
| 9895 | } |
| 9896 | |
| 9897 | S.referenceDLLExportedClassMethods(); |
| 9898 | } |
| 9899 | |
| 9900 | // Explicit instantiation of a class template specialization |
| 9901 | DeclResult Sema::ActOnExplicitInstantiation( |
| 9902 | Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, |
| 9903 | unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, |
| 9904 | TemplateTy TemplateD, SourceLocation TemplateNameLoc, |
| 9905 | SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, |
| 9906 | SourceLocation RAngleLoc, const ParsedAttributesView &Attr) { |
| 9907 | // Find the class template we're specializing |
| 9908 | TemplateName Name = TemplateD.get(); |
| 9909 | TemplateDecl *TD = Name.getAsTemplateDecl(); |
| 9910 | // Check that the specialization uses the same tag kind as the |
| 9911 | // original template. |
| 9912 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
| 9913 | assert(Kind != TTK_Enum &&(static_cast <bool> (Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!" ) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\"" , "clang/lib/Sema/SemaTemplate.cpp", 9914, __extension__ __PRETTY_FUNCTION__ )) |
| 9914 | "Invalid enum tag in class template explicit instantiation!")(static_cast <bool> (Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!" ) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\"" , "clang/lib/Sema/SemaTemplate.cpp", 9914, __extension__ __PRETTY_FUNCTION__ )); |
| 9915 | |
| 9916 | ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD); |
| 9917 | |
| 9918 | if (!ClassTemplate) { |
| 9919 | NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind); |
| 9920 | Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind; |
| 9921 | Diag(TD->getLocation(), diag::note_previous_use); |
| 9922 | return true; |
| 9923 | } |
| 9924 | |
| 9925 | if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), |
| 9926 | Kind, /*isDefinition*/false, KWLoc, |
| 9927 | ClassTemplate->getIdentifier())) { |
| 9928 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
| 9929 | << ClassTemplate |
| 9930 | << FixItHint::CreateReplacement(KWLoc, |
| 9931 | ClassTemplate->getTemplatedDecl()->getKindName()); |
| 9932 | Diag(ClassTemplate->getTemplatedDecl()->getLocation(), |
| 9933 | diag::note_previous_use); |
| 9934 | Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); |
| 9935 | } |
| 9936 | |
| 9937 | // C++0x [temp.explicit]p2: |
| 9938 | // There are two forms of explicit instantiation: an explicit instantiation |
| 9939 | // definition and an explicit instantiation declaration. An explicit |
| 9940 | // instantiation declaration begins with the extern keyword. [...] |
| 9941 | TemplateSpecializationKind TSK = ExternLoc.isInvalid() |
| 9942 | ? TSK_ExplicitInstantiationDefinition |
| 9943 | : TSK_ExplicitInstantiationDeclaration; |
| 9944 | |
| 9945 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
| 9946 | !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { |
| 9947 | // Check for dllexport class template instantiation declarations, |
| 9948 | // except for MinGW mode. |
| 9949 | for (const ParsedAttr &AL : Attr) { |
| 9950 | if (AL.getKind() == ParsedAttr::AT_DLLExport) { |
| 9951 | Diag(ExternLoc, |
| 9952 | diag::warn_attribute_dllexport_explicit_instantiation_decl); |
| 9953 | Diag(AL.getLoc(), diag::note_attribute); |
| 9954 | break; |
| 9955 | } |
| 9956 | } |
| 9957 | |
| 9958 | if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) { |
| 9959 | Diag(ExternLoc, |
| 9960 | diag::warn_attribute_dllexport_explicit_instantiation_decl); |
| 9961 | Diag(A->getLocation(), diag::note_attribute); |
| 9962 | } |
| 9963 | } |
| 9964 | |
| 9965 | // In MSVC mode, dllimported explicit instantiation definitions are treated as |
| 9966 | // instantiation declarations for most purposes. |
| 9967 | bool DLLImportExplicitInstantiationDef = false; |
| 9968 | if (TSK == TSK_ExplicitInstantiationDefinition && |
| 9969 | Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
| 9970 | // Check for dllimport class template instantiation definitions. |
| 9971 | bool DLLImport = |
| 9972 | ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>(); |
| 9973 | for (const ParsedAttr &AL : Attr) { |
| 9974 | if (AL.getKind() == ParsedAttr::AT_DLLImport) |
| 9975 | DLLImport = true; |
| 9976 | if (AL.getKind() == ParsedAttr::AT_DLLExport) { |
| 9977 | // dllexport trumps dllimport here. |
| 9978 | DLLImport = false; |
| 9979 | break; |
| 9980 | } |
| 9981 | } |
| 9982 | if (DLLImport) { |
| 9983 | TSK = TSK_ExplicitInstantiationDeclaration; |
| 9984 | DLLImportExplicitInstantiationDef = true; |
| 9985 | } |
| 9986 | } |
| 9987 | |
| 9988 | // Translate the parser's template argument list in our AST format. |
| 9989 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
| 9990 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
| 9991 | |
| 9992 | // Check that the template argument list is well-formed for this |
| 9993 | // template. |
| 9994 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
| 9995 | if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, |
| 9996 | false, SugaredConverted, CanonicalConverted, |
| 9997 | /*UpdateArgsWithConversions=*/true)) |
| 9998 | return true; |
| 9999 | |
| 10000 | // Find the class template specialization declaration that |
| 10001 | // corresponds to these arguments. |
| 10002 | void *InsertPos = nullptr; |
| 10003 | ClassTemplateSpecializationDecl *PrevDecl = |
| 10004 | ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); |
| 10005 | |
| 10006 | TemplateSpecializationKind PrevDecl_TSK |
| 10007 | = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; |
| 10008 | |
| 10009 | if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr && |
| 10010 | Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { |
| 10011 | // Check for dllexport class template instantiation definitions in MinGW |
| 10012 | // mode, if a previous declaration of the instantiation was seen. |
| 10013 | for (const ParsedAttr &AL : Attr) { |
| 10014 | if (AL.getKind() == ParsedAttr::AT_DLLExport) { |
| 10015 | Diag(AL.getLoc(), |
| 10016 | diag::warn_attribute_dllexport_explicit_instantiation_def); |
| 10017 | break; |
| 10018 | } |
| 10019 | } |
| 10020 | } |
| 10021 | |
| 10022 | if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc, |
| 10023 | SS.isSet(), TSK)) |
| 10024 | return true; |
| 10025 | |
| 10026 | ClassTemplateSpecializationDecl *Specialization = nullptr; |
| 10027 | |
| 10028 | bool HasNoEffect = false; |
| 10029 | if (PrevDecl) { |
| 10030 | if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, |
| 10031 | PrevDecl, PrevDecl_TSK, |
| 10032 | PrevDecl->getPointOfInstantiation(), |
| 10033 | HasNoEffect)) |
| 10034 | return PrevDecl; |
| 10035 | |
| 10036 | // Even though HasNoEffect == true means that this explicit instantiation |
| 10037 | // has no effect on semantics, we go on to put its syntax in the AST. |
| 10038 | |
| 10039 | if (PrevDecl_TSK == TSK_ImplicitInstantiation || |
| 10040 | PrevDecl_TSK == TSK_Undeclared) { |
| 10041 | // Since the only prior class template specialization with these |
| 10042 | // arguments was referenced but not declared, reuse that |
| 10043 | // declaration node as our own, updating the source location |
| 10044 | // for the template name to reflect our new declaration. |
| 10045 | // (Other source locations will be updated later.) |
| 10046 | Specialization = PrevDecl; |
| 10047 | Specialization->setLocation(TemplateNameLoc); |
| 10048 | PrevDecl = nullptr; |
| 10049 | } |
| 10050 | |
| 10051 | if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && |
| 10052 | DLLImportExplicitInstantiationDef) { |
| 10053 | // The new specialization might add a dllimport attribute. |
| 10054 | HasNoEffect = false; |
| 10055 | } |
| 10056 | } |
| 10057 | |
| 10058 | if (!Specialization) { |
| 10059 | // Create a new class template specialization declaration node for |
| 10060 | // this explicit specialization. |
| 10061 | Specialization = ClassTemplateSpecializationDecl::Create( |
| 10062 | Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc, |
| 10063 | ClassTemplate, CanonicalConverted, PrevDecl); |
| 10064 | SetNestedNameSpecifier(*this, Specialization, SS); |
| 10065 | |
| 10066 | if (!HasNoEffect && !PrevDecl) { |
| 10067 | // Insert the new specialization. |
| 10068 | ClassTemplate->AddSpecialization(Specialization, InsertPos); |
| 10069 | } |
| 10070 | } |
| 10071 | |
| 10072 | // Build the fully-sugared type for this explicit instantiation as |
| 10073 | // the user wrote in the explicit instantiation itself. This means |
| 10074 | // that we'll pretty-print the type retrieved from the |
| 10075 | // specialization's declaration the way that the user actually wrote |
| 10076 | // the explicit instantiation, rather than formatting the name based |
| 10077 | // on the "canonical" representation used to store the template |
| 10078 | // arguments in the specialization. |
| 10079 | TypeSourceInfo *WrittenTy |
| 10080 | = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, |
| 10081 | TemplateArgs, |
| 10082 | Context.getTypeDeclType(Specialization)); |
| 10083 | Specialization->setTypeAsWritten(WrittenTy); |
| 10084 | |
| 10085 | // Set source locations for keywords. |
| 10086 | Specialization->setExternLoc(ExternLoc); |
| 10087 | Specialization->setTemplateKeywordLoc(TemplateLoc); |
| 10088 | Specialization->setBraceRange(SourceRange()); |
| 10089 | |
| 10090 | bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>(); |
| 10091 | ProcessDeclAttributeList(S, Specialization, Attr); |
| 10092 | |
| 10093 | // Add the explicit instantiation into its lexical context. However, |
| 10094 | // since explicit instantiations are never found by name lookup, we |
| 10095 | // just put it into the declaration context directly. |
| 10096 | Specialization->setLexicalDeclContext(CurContext); |
| 10097 | CurContext->addDecl(Specialization); |
| 10098 | |
| 10099 | // Syntax is now OK, so return if it has no other effect on semantics. |
| 10100 | if (HasNoEffect) { |
| 10101 | // Set the template specialization kind. |
| 10102 | Specialization->setTemplateSpecializationKind(TSK); |
| 10103 | return Specialization; |
| 10104 | } |
| 10105 | |
| 10106 | // C++ [temp.explicit]p3: |
| 10107 | // A definition of a class template or class member template |
| 10108 | // shall be in scope at the point of the explicit instantiation of |
| 10109 | // the class template or class member template. |
| 10110 | // |
| 10111 | // This check comes when we actually try to perform the |
| 10112 | // instantiation. |
| 10113 | ClassTemplateSpecializationDecl *Def |
| 10114 | = cast_or_null<ClassTemplateSpecializationDecl>( |
| 10115 | Specialization->getDefinition()); |
| 10116 | if (!Def) |
| 10117 | InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); |
| 10118 | else if (TSK == TSK_ExplicitInstantiationDefinition) { |
| 10119 | MarkVTableUsed(TemplateNameLoc, Specialization, true); |
| 10120 | Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); |
| 10121 | } |
| 10122 | |
| 10123 | // Instantiate the members of this class template specialization. |
| 10124 | Def = cast_or_null<ClassTemplateSpecializationDecl>( |
| 10125 | Specialization->getDefinition()); |
| 10126 | if (Def) { |
| 10127 | TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); |
| 10128 | // Fix a TSK_ExplicitInstantiationDeclaration followed by a |
| 10129 | // TSK_ExplicitInstantiationDefinition |
| 10130 | if (Old_TSK == TSK_ExplicitInstantiationDeclaration && |
| 10131 | (TSK == TSK_ExplicitInstantiationDefinition || |
| 10132 | DLLImportExplicitInstantiationDef)) { |
| 10133 | // FIXME: Need to notify the ASTMutationListener that we did this. |
| 10134 | Def->setTemplateSpecializationKind(TSK); |
| 10135 | |
| 10136 | if (!getDLLAttr(Def) && getDLLAttr(Specialization) && |
| 10137 | (Context.getTargetInfo().shouldDLLImportComdatSymbols() && |
| 10138 | !Context.getTargetInfo().getTriple().isPS())) { |
| 10139 | // An explicit instantiation definition can add a dll attribute to a |
| 10140 | // template with a previous instantiation declaration. MinGW doesn't |
| 10141 | // allow this. |
| 10142 | auto *A = cast<InheritableAttr>( |
| 10143 | getDLLAttr(Specialization)->clone(getASTContext())); |
| 10144 | A->setInherited(true); |
| 10145 | Def->addAttr(A); |
| 10146 | dllExportImportClassTemplateSpecialization(*this, Def); |
| 10147 | } |
| 10148 | } |
| 10149 | |
| 10150 | // Fix a TSK_ImplicitInstantiation followed by a |
| 10151 | // TSK_ExplicitInstantiationDefinition |
| 10152 | bool NewlyDLLExported = |
| 10153 | !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>(); |
| 10154 | if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported && |
| 10155 | (Context.getTargetInfo().shouldDLLImportComdatSymbols() && |
| 10156 | !Context.getTargetInfo().getTriple().isPS())) { |
| 10157 | // An explicit instantiation definition can add a dll attribute to a |
| 10158 | // template with a previous implicit instantiation. MinGW doesn't allow |
| 10159 | // this. We limit clang to only adding dllexport, to avoid potentially |
| 10160 | // strange codegen behavior. For example, if we extend this conditional |
| 10161 | // to dllimport, and we have a source file calling a method on an |
| 10162 | // implicitly instantiated template class instance and then declaring a |
| 10163 | // dllimport explicit instantiation definition for the same template |
| 10164 | // class, the codegen for the method call will not respect the dllimport, |
| 10165 | // while it will with cl. The Def will already have the DLL attribute, |
| 10166 | // since the Def and Specialization will be the same in the case of |
| 10167 | // Old_TSK == TSK_ImplicitInstantiation, and we already added the |
| 10168 | // attribute to the Specialization; we just need to make it take effect. |
| 10169 | assert(Def == Specialization &&(static_cast <bool> (Def == Specialization && "Def and Specialization should match for implicit instantiation" ) ? void (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\"" , "clang/lib/Sema/SemaTemplate.cpp", 10170, __extension__ __PRETTY_FUNCTION__ )) |
| 10170 | "Def and Specialization should match for implicit instantiation")(static_cast <bool> (Def == Specialization && "Def and Specialization should match for implicit instantiation" ) ? void (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\"" , "clang/lib/Sema/SemaTemplate.cpp", 10170, __extension__ __PRETTY_FUNCTION__ )); |
| 10171 | dllExportImportClassTemplateSpecialization(*this, Def); |
| 10172 | } |
| 10173 | |
| 10174 | // In MinGW mode, export the template instantiation if the declaration |
| 10175 | // was marked dllexport. |
| 10176 | if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && |
| 10177 | Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() && |
| 10178 | PrevDecl->hasAttr<DLLExportAttr>()) { |
| 10179 | dllExportImportClassTemplateSpecialization(*this, Def); |
| 10180 | } |
| 10181 | |
| 10182 | if (Def->hasAttr<MSInheritanceAttr>()) { |
| 10183 | Specialization->addAttr(Def->getAttr<MSInheritanceAttr>()); |
| 10184 | Consumer.AssignInheritanceModel(Specialization); |
| 10185 | } |
| 10186 | |
| 10187 | // Set the template specialization kind. Make sure it is set before |
| 10188 | // instantiating the members which will trigger ASTConsumer callbacks. |
| 10189 | Specialization->setTemplateSpecializationKind(TSK); |
| 10190 | InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); |
| 10191 | } else { |
| 10192 | |
| 10193 | // Set the template specialization kind. |
| 10194 | Specialization->setTemplateSpecializationKind(TSK); |
| 10195 | } |
| 10196 | |
| 10197 | return Specialization; |
| 10198 | } |
| 10199 | |
| 10200 | // Explicit instantiation of a member class of a class template. |
| 10201 | DeclResult |
| 10202 | Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, |
| 10203 | SourceLocation TemplateLoc, unsigned TagSpec, |
| 10204 | SourceLocation KWLoc, CXXScopeSpec &SS, |
| 10205 | IdentifierInfo *Name, SourceLocation NameLoc, |
| 10206 | const ParsedAttributesView &Attr) { |
| 10207 | |
| 10208 | bool Owned = false; |
| 10209 | bool IsDependent = false; |
| 10210 | Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name, |
| 10211 | NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(), |
| 10212 | MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(), |
| 10213 | false, TypeResult(), /*IsTypeSpecifier*/ false, |
| 10214 | /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get(); |
| 10215 | assert(!IsDependent && "explicit instantiation of dependent name not yet handled")(static_cast <bool> (!IsDependent && "explicit instantiation of dependent name not yet handled" ) ? void (0) : __assert_fail ("!IsDependent && \"explicit instantiation of dependent name not yet handled\"" , "clang/lib/Sema/SemaTemplate.cpp", 10215, __extension__ __PRETTY_FUNCTION__ )); |
| 10216 | |
| 10217 | if (!TagD) |
| 10218 | return true; |
| 10219 | |
| 10220 | TagDecl *Tag = cast<TagDecl>(TagD); |
| 10221 | assert(!Tag->isEnum() && "shouldn't see enumerations here")(static_cast <bool> (!Tag->isEnum() && "shouldn't see enumerations here" ) ? void (0) : __assert_fail ("!Tag->isEnum() && \"shouldn't see enumerations here\"" , "clang/lib/Sema/SemaTemplate.cpp", 10221, __extension__ __PRETTY_FUNCTION__ )); |
| 10222 | |
| 10223 | if (Tag->isInvalidDecl()) |
| 10224 | return true; |
| 10225 | |
| 10226 | CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); |
| 10227 | CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); |
| 10228 | if (!Pattern) { |
| 10229 | Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) |
| 10230 | << Context.getTypeDeclType(Record); |
| 10231 | Diag(Record->getLocation(), diag::note_nontemplate_decl_here); |
| 10232 | return true; |
| 10233 | } |
| 10234 | |
| 10235 | // C++0x [temp.explicit]p2: |
| 10236 | // If the explicit instantiation is for a class or member class, the |
| 10237 | // elaborated-type-specifier in the declaration shall include a |
| 10238 | // simple-template-id. |
| 10239 | // |
| 10240 | // C++98 has the same restriction, just worded differently. |
| 10241 | if (!ScopeSpecifierHasTemplateId(SS)) |
| 10242 | Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) |
| 10243 | << Record << SS.getRange(); |
| 10244 | |
| 10245 | // C++0x [temp.explicit]p2: |
| 10246 | // There are two forms of explicit instantiation: an explicit instantiation |
| 10247 | // definition and an explicit instantiation declaration. An explicit |
| 10248 | // instantiation declaration begins with the extern keyword. [...] |
| 10249 | TemplateSpecializationKind TSK |
| 10250 | = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition |
| 10251 | : TSK_ExplicitInstantiationDeclaration; |
| 10252 | |
| 10253 | CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK); |
| 10254 | |
| 10255 | // Verify that it is okay to explicitly instantiate here. |
| 10256 | CXXRecordDecl *PrevDecl |
| 10257 | = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl()); |
| 10258 | if (!PrevDecl && Record->getDefinition()) |
| 10259 | PrevDecl = Record; |
| 10260 | if (PrevDecl) { |
| 10261 | MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); |
| 10262 | bool HasNoEffect = false; |
| 10263 | assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?" ) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\"" , "clang/lib/Sema/SemaTemplate.cpp", 10263, __extension__ __PRETTY_FUNCTION__ )); |
| 10264 | if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, |
| 10265 | PrevDecl, |
| 10266 | MSInfo->getTemplateSpecializationKind(), |
| 10267 | MSInfo->getPointOfInstantiation(), |
| 10268 | HasNoEffect)) |
| 10269 | return true; |
| 10270 | if (HasNoEffect) |
| 10271 | return TagD; |
| 10272 | } |
| 10273 | |
| 10274 | CXXRecordDecl *RecordDef |
| 10275 | = cast_or_null<CXXRecordDecl>(Record->getDefinition()); |
| 10276 | if (!RecordDef) { |
| 10277 | // C++ [temp.explicit]p3: |
| 10278 | // A definition of a member class of a class template shall be in scope |
| 10279 | // at the point of an explicit instantiation of the member class. |
| 10280 | CXXRecordDecl *Def |
| 10281 | = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); |
| 10282 | if (!Def) { |
| 10283 | Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) |
| 10284 | << 0 << Record->getDeclName() << Record->getDeclContext(); |
| 10285 | Diag(Pattern->getLocation(), diag::note_forward_declaration) |
| 10286 | << Pattern; |
| 10287 | return true; |
| 10288 | } else { |
| 10289 | if (InstantiateClass(NameLoc, Record, Def, |
| 10290 | getTemplateInstantiationArgs(Record), |
| 10291 | TSK)) |
| 10292 | return true; |
| 10293 | |
| 10294 | RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); |
| 10295 | if (!RecordDef) |
| 10296 | return true; |
| 10297 | } |
| 10298 | } |
| 10299 | |
| 10300 | // Instantiate all of the members of the class. |
| 10301 | InstantiateClassMembers(NameLoc, RecordDef, |
| 10302 | getTemplateInstantiationArgs(Record), TSK); |
| 10303 | |
| 10304 | if (TSK == TSK_ExplicitInstantiationDefinition) |
| 10305 | MarkVTableUsed(NameLoc, RecordDef, true); |
| 10306 | |
| 10307 | // FIXME: We don't have any representation for explicit instantiations of |
| 10308 | // member classes. Such a representation is not needed for compilation, but it |
| 10309 | // should be available for clients that want to see all of the declarations in |
| 10310 | // the source code. |
| 10311 | return TagD; |
| 10312 | } |
| 10313 | |
| 10314 | DeclResult Sema::ActOnExplicitInstantiation(Scope *S, |
| 10315 | SourceLocation ExternLoc, |
| 10316 | SourceLocation TemplateLoc, |
| 10317 | Declarator &D) { |
| 10318 | // Explicit instantiations always require a name. |
| 10319 | // TODO: check if/when DNInfo should replace Name. |
| 10320 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
| 10321 | DeclarationName Name = NameInfo.getName(); |
| 10322 | if (!Name) { |
| 10323 | if (!D.isInvalidType()) |
| 10324 | Diag(D.getDeclSpec().getBeginLoc(), |
| 10325 | diag::err_explicit_instantiation_requires_name) |
| 10326 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); |
| 10327 | |
| 10328 | return true; |
| 10329 | } |
| 10330 | |
| 10331 | // The scope passed in may not be a decl scope. Zip up the scope tree until |
| 10332 | // we find one that is. |
| 10333 | while ((S->getFlags() & Scope::DeclScope) == 0 || |
| 10334 | (S->getFlags() & Scope::TemplateParamScope) != 0) |
| 10335 | S = S->getParent(); |
| 10336 | |
| 10337 | // Determine the type of the declaration. |
| 10338 | TypeSourceInfo *T = GetTypeForDeclarator(D, S); |
| 10339 | QualType R = T->getType(); |
| 10340 | if (R.isNull()) |
| 10341 | return true; |
| 10342 | |
| 10343 | // C++ [dcl.stc]p1: |
| 10344 | // A storage-class-specifier shall not be specified in [...] an explicit |
| 10345 | // instantiation (14.7.2) directive. |
| 10346 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { |
| 10347 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) |
| 10348 | << Name; |
| 10349 | return true; |
| 10350 | } else if (D.getDeclSpec().getStorageClassSpec() |
| 10351 | != DeclSpec::SCS_unspecified) { |
| 10352 | // Complain about then remove the storage class specifier. |
| 10353 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class) |
| 10354 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); |
| 10355 | |
| 10356 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
| 10357 | } |
| 10358 | |
| 10359 | // C++0x [temp.explicit]p1: |
| 10360 | // [...] An explicit instantiation of a function template shall not use the |
| 10361 | // inline or constexpr specifiers. |
| 10362 | // Presumably, this also applies to member functions of class templates as |
| 10363 | // well. |
| 10364 | if (D.getDeclSpec().isInlineSpecified()) |
| 10365 | Diag(D.getDeclSpec().getInlineSpecLoc(), |
| 10366 | getLangOpts().CPlusPlus11 ? |
| 10367 | diag::err_explicit_instantiation_inline : |
| 10368 | diag::warn_explicit_instantiation_inline_0x) |
| 10369 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); |
| 10370 | if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType()) |
| 10371 | // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is |
| 10372 | // not already specified. |
| 10373 | Diag(D.getDeclSpec().getConstexprSpecLoc(), |
| 10374 | diag::err_explicit_instantiation_constexpr); |
| 10375 | |
| 10376 | // A deduction guide is not on the list of entities that can be explicitly |
| 10377 | // instantiated. |
| 10378 | if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { |
| 10379 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized) |
| 10380 | << /*explicit instantiation*/ 0; |
| 10381 | return true; |
| 10382 | } |
| 10383 | |
| 10384 | // C++0x [temp.explicit]p2: |
| 10385 | // There are two forms of explicit instantiation: an explicit instantiation |
| 10386 | // definition and an explicit instantiation declaration. An explicit |
| 10387 | // instantiation declaration begins with the extern keyword. [...] |
| 10388 | TemplateSpecializationKind TSK |
| 10389 | = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition |
| 10390 | : TSK_ExplicitInstantiationDeclaration; |
| 10391 | |
| 10392 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName); |
| 10393 | LookupParsedName(Previous, S, &D.getCXXScopeSpec()); |
| 10394 | |
| 10395 | if (!R->isFunctionType()) { |
| 10396 | // C++ [temp.explicit]p1: |
| 10397 | // A [...] static data member of a class template can be explicitly |
| 10398 | // instantiated from the member definition associated with its class |
| 10399 | // template. |
| 10400 | // C++1y [temp.explicit]p1: |
| 10401 | // A [...] variable [...] template specialization can be explicitly |
| 10402 | // instantiated from its template. |
| 10403 | if (Previous.isAmbiguous()) |
| 10404 | return true; |
| 10405 | |
| 10406 | VarDecl *Prev = Previous.getAsSingle<VarDecl>(); |
| 10407 | VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>(); |
| 10408 | |
| 10409 | if (!PrevTemplate) { |
| 10410 | if (!Prev || !Prev->isStaticDataMember()) { |
| 10411 | // We expect to see a static data member here. |
| 10412 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) |
| 10413 | << Name; |
| 10414 | for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); |
| 10415 | P != PEnd; ++P) |
| 10416 | Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); |
| 10417 | return true; |
| 10418 | } |
| 10419 | |
| 10420 | if (!Prev->getInstantiatedFromStaticDataMember()) { |
| 10421 | // FIXME: Check for explicit specialization? |
| 10422 | Diag(D.getIdentifierLoc(), |
| 10423 | diag::err_explicit_instantiation_data_member_not_instantiated) |
| 10424 | << Prev; |
| 10425 | Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); |
| 10426 | // FIXME: Can we provide a note showing where this was declared? |
| 10427 | return true; |
| 10428 | } |
| 10429 | } else { |
| 10430 | // Explicitly instantiate a variable template. |
| 10431 | |
| 10432 | // C++1y [dcl.spec.auto]p6: |
| 10433 | // ... A program that uses auto or decltype(auto) in a context not |
| 10434 | // explicitly allowed in this section is ill-formed. |
| 10435 | // |
| 10436 | // This includes auto-typed variable template instantiations. |
| 10437 | if (R->isUndeducedType()) { |
| 10438 | Diag(T->getTypeLoc().getBeginLoc(), |
| 10439 | diag::err_auto_not_allowed_var_inst); |
| 10440 | return true; |
| 10441 | } |
| 10442 | |
| 10443 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { |
| 10444 | // C++1y [temp.explicit]p3: |
| 10445 | // If the explicit instantiation is for a variable, the unqualified-id |
| 10446 | // in the declaration shall be a template-id. |
| 10447 | Diag(D.getIdentifierLoc(), |
| 10448 | diag::err_explicit_instantiation_without_template_id) |
| 10449 | << PrevTemplate; |
| 10450 | Diag(PrevTemplate->getLocation(), |
| 10451 | diag::note_explicit_instantiation_here); |
| 10452 | return true; |
| 10453 | } |
| 10454 | |
| 10455 | // Translate the parser's template argument list into our AST format. |
| 10456 | TemplateArgumentListInfo TemplateArgs = |
| 10457 | makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); |
| 10458 | |
| 10459 | DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc, |
| 10460 | D.getIdentifierLoc(), TemplateArgs); |
| 10461 | if (Res.isInvalid()) |
| 10462 | return true; |
| 10463 | |
| 10464 | if (!Res.isUsable()) { |
| 10465 | // We somehow specified dependent template arguments in an explicit |
| 10466 | // instantiation. This should probably only happen during error |
| 10467 | // recovery. |
| 10468 | Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent); |
| 10469 | return true; |
| 10470 | } |
| 10471 | |
| 10472 | // Ignore access control bits, we don't need them for redeclaration |
| 10473 | // checking. |
| 10474 | Prev = cast<VarDecl>(Res.get()); |
| 10475 | } |
| 10476 | |
| 10477 | // C++0x [temp.explicit]p2: |
| 10478 | // If the explicit instantiation is for a member function, a member class |
| 10479 | // or a static data member of a class template specialization, the name of |
| 10480 | // the class template specialization in the qualified-id for the member |
| 10481 | // name shall be a simple-template-id. |
| 10482 | // |
| 10483 | // C++98 has the same restriction, just worded differently. |
| 10484 | // |
| 10485 | // This does not apply to variable template specializations, where the |
| 10486 | // template-id is in the unqualified-id instead. |
| 10487 | if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate) |
| 10488 | Diag(D.getIdentifierLoc(), |
| 10489 | diag::ext_explicit_instantiation_without_qualified_id) |
| 10490 | << Prev << D.getCXXScopeSpec().getRange(); |
| 10491 | |
| 10492 | CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK); |
| 10493 | |
| 10494 | // Verify that it is okay to explicitly instantiate here. |
| 10495 | TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind(); |
| 10496 | SourceLocation POI = Prev->getPointOfInstantiation(); |
| 10497 | bool HasNoEffect = false; |
| 10498 | if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, |
| 10499 | PrevTSK, POI, HasNoEffect)) |
| 10500 | return true; |
| 10501 | |
| 10502 | if (!HasNoEffect) { |
| 10503 | // Instantiate static data member or variable template. |
| 10504 | Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); |
| 10505 | // Merge attributes. |
| 10506 | ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes()); |
| 10507 | if (TSK == TSK_ExplicitInstantiationDefinition) |
| 10508 | InstantiateVariableDefinition(D.getIdentifierLoc(), Prev); |
| 10509 | } |
| 10510 | |
| 10511 | // Check the new variable specialization against the parsed input. |
| 10512 | if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) { |
| 10513 | Diag(T->getTypeLoc().getBeginLoc(), |
| 10514 | diag::err_invalid_var_template_spec_type) |
| 10515 | << 0 << PrevTemplate << R << Prev->getType(); |
| 10516 | Diag(PrevTemplate->getLocation(), diag::note_template_declared_here) |
| 10517 | << 2 << PrevTemplate->getDeclName(); |
| 10518 | return true; |
| 10519 | } |
| 10520 | |
| 10521 | // FIXME: Create an ExplicitInstantiation node? |
| 10522 | return (Decl*) nullptr; |
| 10523 | } |
| 10524 | |
| 10525 | // If the declarator is a template-id, translate the parser's template |
| 10526 | // argument list into our AST format. |
| 10527 | bool HasExplicitTemplateArgs = false; |
| 10528 | TemplateArgumentListInfo TemplateArgs; |
| 10529 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { |
| 10530 | TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); |
| 10531 | HasExplicitTemplateArgs = true; |
| 10532 | } |
| 10533 | |
| 10534 | // C++ [temp.explicit]p1: |
| 10535 | // A [...] function [...] can be explicitly instantiated from its template. |
| 10536 | // A member function [...] of a class template can be explicitly |
| 10537 | // instantiated from the member definition associated with its class |
| 10538 | // template. |
| 10539 | UnresolvedSet<8> TemplateMatches; |
| 10540 | FunctionDecl *NonTemplateMatch = nullptr; |
| 10541 | TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc()); |
| 10542 | for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); |
| 10543 | P != PEnd; ++P) { |
| 10544 | NamedDecl *Prev = *P; |
| 10545 | if (!HasExplicitTemplateArgs) { |
| 10546 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { |
| 10547 | QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(), |
| 10548 | /*AdjustExceptionSpec*/true); |
| 10549 | if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) { |
| 10550 | if (Method->getPrimaryTemplate()) { |
| 10551 | TemplateMatches.addDecl(Method, P.getAccess()); |
| 10552 | } else { |
| 10553 | // FIXME: Can this assert ever happen? Needs a test. |
| 10554 | assert(!NonTemplateMatch && "Multiple NonTemplateMatches")(static_cast <bool> (!NonTemplateMatch && "Multiple NonTemplateMatches" ) ? void (0) : __assert_fail ("!NonTemplateMatch && \"Multiple NonTemplateMatches\"" , "clang/lib/Sema/SemaTemplate.cpp", 10554, __extension__ __PRETTY_FUNCTION__ )); |
| 10555 | NonTemplateMatch = Method; |
| 10556 | } |
| 10557 | } |
| 10558 | } |
| 10559 | } |
| 10560 | |
| 10561 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); |
| 10562 | if (!FunTmpl) |
| 10563 | continue; |
| 10564 | |
| 10565 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
| 10566 | FunctionDecl *Specialization = nullptr; |
| 10567 | if (TemplateDeductionResult TDK |
| 10568 | = DeduceTemplateArguments(FunTmpl, |
| 10569 | (HasExplicitTemplateArgs ? &TemplateArgs |
| 10570 | : nullptr), |
| 10571 | R, Specialization, Info)) { |
| 10572 | // Keep track of almost-matches. |
| 10573 | FailedCandidates.addCandidate() |
| 10574 | .set(P.getPair(), FunTmpl->getTemplatedDecl(), |
| 10575 | MakeDeductionFailureInfo(Context, TDK, Info)); |
| 10576 | (void)TDK; |
| 10577 | continue; |
| 10578 | } |
| 10579 | |
| 10580 | // Target attributes are part of the cuda function signature, so |
| 10581 | // the cuda target of the instantiated function must match that of its |
| 10582 | // template. Given that C++ template deduction does not take |
| 10583 | // target attributes into account, we reject candidates here that |
| 10584 | // have a different target. |
| 10585 | if (LangOpts.CUDA && |
| 10586 | IdentifyCUDATarget(Specialization, |
| 10587 | /* IgnoreImplicitHDAttr = */ true) != |
| 10588 | IdentifyCUDATarget(D.getDeclSpec().getAttributes())) { |
| 10589 | FailedCandidates.addCandidate().set( |
| 10590 | P.getPair(), FunTmpl->getTemplatedDecl(), |
| 10591 | MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); |
| 10592 | continue; |
| 10593 | } |
| 10594 | |
| 10595 | TemplateMatches.addDecl(Specialization, P.getAccess()); |
| 10596 | } |
| 10597 | |
| 10598 | FunctionDecl *Specialization = NonTemplateMatch; |
| 10599 | if (!Specialization) { |
| 10600 | // Find the most specialized function template specialization. |
| 10601 | UnresolvedSetIterator Result = getMostSpecialized( |
| 10602 | TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates, |
| 10603 | D.getIdentifierLoc(), |
| 10604 | PDiag(diag::err_explicit_instantiation_not_known) << Name, |
| 10605 | PDiag(diag::err_explicit_instantiation_ambiguous) << Name, |
| 10606 | PDiag(diag::note_explicit_instantiation_candidate)); |
| 10607 | |
| 10608 | if (Result == TemplateMatches.end()) |
| 10609 | return true; |
| 10610 | |
| 10611 | // Ignore access control bits, we don't need them for redeclaration checking. |
| 10612 | Specialization = cast<FunctionDecl>(*Result); |
| 10613 | } |
| 10614 | |
| 10615 | // C++11 [except.spec]p4 |
| 10616 | // In an explicit instantiation an exception-specification may be specified, |
| 10617 | // but is not required. |
| 10618 | // If an exception-specification is specified in an explicit instantiation |
| 10619 | // directive, it shall be compatible with the exception-specifications of |
| 10620 | // other declarations of that function. |
| 10621 | if (auto *FPT = R->getAs<FunctionProtoType>()) |
| 10622 | if (FPT->hasExceptionSpec()) { |
| 10623 | unsigned DiagID = |
| 10624 | diag::err_mismatched_exception_spec_explicit_instantiation; |
| 10625 | if (getLangOpts().MicrosoftExt) |
| 10626 | DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation; |
| 10627 | bool Result = CheckEquivalentExceptionSpec( |
| 10628 | PDiag(DiagID) << Specialization->getType(), |
| 10629 | PDiag(diag::note_explicit_instantiation_here), |
| 10630 | Specialization->getType()->getAs<FunctionProtoType>(), |
| 10631 | Specialization->getLocation(), FPT, D.getBeginLoc()); |
| 10632 | // In Microsoft mode, mismatching exception specifications just cause a |
| 10633 | // warning. |
| 10634 | if (!getLangOpts().MicrosoftExt && Result) |
| 10635 | return true; |
| 10636 | } |
| 10637 | |
| 10638 | if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { |
| 10639 | Diag(D.getIdentifierLoc(), |
| 10640 | diag::err_explicit_instantiation_member_function_not_instantiated) |
| 10641 | << Specialization |
| 10642 | << (Specialization->getTemplateSpecializationKind() == |
| 10643 | TSK_ExplicitSpecialization); |
| 10644 | Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); |
| 10645 | return true; |
| 10646 | } |
| 10647 | |
| 10648 | FunctionDecl *PrevDecl = Specialization->getPreviousDecl(); |
| 10649 | if (!PrevDecl && Specialization->isThisDeclarationADefinition()) |
| 10650 | PrevDecl = Specialization; |
| 10651 | |
| 10652 | if (PrevDecl) { |
| 10653 | bool HasNoEffect = false; |
| 10654 | if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, |
| 10655 | PrevDecl, |
| 10656 | PrevDecl->getTemplateSpecializationKind(), |
| 10657 | PrevDecl->getPointOfInstantiation(), |
| 10658 | HasNoEffect)) |
| 10659 | return true; |
| 10660 | |
| 10661 | // FIXME: We may still want to build some representation of this |
| 10662 | // explicit specialization. |
| 10663 | if (HasNoEffect) |
| 10664 | return (Decl*) nullptr; |
| 10665 | } |
| 10666 | |
| 10667 | // HACK: libc++ has a bug where it attempts to explicitly instantiate the |
| 10668 | // functions |
| 10669 | // valarray<size_t>::valarray(size_t) and |
| 10670 | // valarray<size_t>::~valarray() |
| 10671 | // that it declared to have internal linkage with the internal_linkage |
| 10672 | // attribute. Ignore the explicit instantiation declaration in this case. |
| 10673 | if (Specialization->hasAttr<InternalLinkageAttr>() && |
| 10674 | TSK == TSK_ExplicitInstantiationDeclaration) { |
| 10675 | if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext())) |
| 10676 | if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") && |
| 10677 | RD->isInStdNamespace()) |
| 10678 | return (Decl*) nullptr; |
| 10679 | } |
| 10680 | |
| 10681 | ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes()); |
| 10682 | |
| 10683 | // In MSVC mode, dllimported explicit instantiation definitions are treated as |
| 10684 | // instantiation declarations. |
| 10685 | if (TSK == TSK_ExplicitInstantiationDefinition && |
| 10686 | Specialization->hasAttr<DLLImportAttr>() && |
| 10687 | Context.getTargetInfo().getCXXABI().isMicrosoft()) |
| 10688 | TSK = TSK_ExplicitInstantiationDeclaration; |
| 10689 | |
| 10690 | Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); |
| 10691 | |
| 10692 | if (Specialization->isDefined()) { |
| 10693 | // Let the ASTConsumer know that this function has been explicitly |
| 10694 | // instantiated now, and its linkage might have changed. |
| 10695 | Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization)); |
| 10696 | } else if (TSK == TSK_ExplicitInstantiationDefinition) |
| 10697 | InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization); |
| 10698 | |
| 10699 | // C++0x [temp.explicit]p2: |
| 10700 | // If the explicit instantiation is for a member function, a member class |
| 10701 | // or a static data member of a class template specialization, the name of |
| 10702 | // the class template specialization in the qualified-id for the member |
| 10703 | // name shall be a simple-template-id. |
| 10704 | // |
| 10705 | // C++98 has the same restriction, just worded differently. |
| 10706 | FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); |
| 10707 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl && |
| 10708 | D.getCXXScopeSpec().isSet() && |
| 10709 | !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) |
| 10710 | Diag(D.getIdentifierLoc(), |
| 10711 | diag::ext_explicit_instantiation_without_qualified_id) |
| 10712 | << Specialization << D.getCXXScopeSpec().getRange(); |
| 10713 | |
| 10714 | CheckExplicitInstantiation( |
| 10715 | *this, |
| 10716 | FunTmpl ? (NamedDecl *)FunTmpl |
| 10717 | : Specialization->getInstantiatedFromMemberFunction(), |
| 10718 | D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK); |
| 10719 | |
| 10720 | // FIXME: Create some kind of ExplicitInstantiationDecl here. |
| 10721 | return (Decl*) nullptr; |
| 10722 | } |
| 10723 | |
| 10724 | TypeResult |
| 10725 | Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, |
| 10726 | const CXXScopeSpec &SS, IdentifierInfo *Name, |
| 10727 | SourceLocation TagLoc, SourceLocation NameLoc) { |
| 10728 | // This has to hold, because SS is expected to be defined. |
| 10729 | assert(Name && "Expected a name in a dependent tag")(static_cast <bool> (Name && "Expected a name in a dependent tag" ) ? void (0) : __assert_fail ("Name && \"Expected a name in a dependent tag\"" , "clang/lib/Sema/SemaTemplate.cpp", 10729, __extension__ __PRETTY_FUNCTION__ )); |
| 10730 | |
| 10731 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
| 10732 | if (!NNS) |
| 10733 | return true; |
| 10734 | |
| 10735 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
| 10736 | |
| 10737 | if (TUK == TUK_Declaration || TUK == TUK_Definition) { |
| 10738 | Diag(NameLoc, diag::err_dependent_tag_decl) |
| 10739 | << (TUK == TUK_Definition) << Kind << SS.getRange(); |
| 10740 | return true; |
| 10741 | } |
| 10742 | |
| 10743 | // Create the resulting type. |
| 10744 | ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind); |
| 10745 | QualType Result = Context.getDependentNameType(Kwd, NNS, Name); |
| 10746 | |
| 10747 | // Create type-source location information for this type. |
| 10748 | TypeLocBuilder TLB; |
| 10749 | DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result); |
| 10750 | TL.setElaboratedKeywordLoc(TagLoc); |
| 10751 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 10752 | TL.setNameLoc(NameLoc); |
| 10753 | return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); |
| 10754 | } |
| 10755 | |
| 10756 | TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, |
| 10757 | const CXXScopeSpec &SS, |
| 10758 | const IdentifierInfo &II, |
| 10759 | SourceLocation IdLoc, |
| 10760 | ImplicitTypenameContext IsImplicitTypename) { |
| 10761 | if (SS.isInvalid()) |
| 10762 | return true; |
| 10763 | |
| 10764 | if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) |
| 10765 | Diag(TypenameLoc, |
| 10766 | getLangOpts().CPlusPlus11 ? |
| 10767 | diag::warn_cxx98_compat_typename_outside_of_template : |
| 10768 | diag::ext_typename_outside_of_template) |
| 10769 | << FixItHint::CreateRemoval(TypenameLoc); |
| 10770 | |
| 10771 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
| 10772 | TypeSourceInfo *TSI = nullptr; |
| 10773 | QualType T = |
| 10774 | CheckTypenameType((TypenameLoc.isValid() || |
| 10775 | IsImplicitTypename == ImplicitTypenameContext::Yes) |
| 10776 | ? ETK_Typename |
| 10777 | : ETK_None, |
| 10778 | TypenameLoc, QualifierLoc, II, IdLoc, &TSI, |
| 10779 | /*DeducedTSTContext=*/true); |
| 10780 | if (T.isNull()) |
| 10781 | return true; |
| 10782 | return CreateParsedType(T, TSI); |
| 10783 | } |
| 10784 | |
| 10785 | TypeResult |
| 10786 | Sema::ActOnTypenameType(Scope *S, |
| 10787 | SourceLocation TypenameLoc, |
| 10788 | const CXXScopeSpec &SS, |
| 10789 | SourceLocation TemplateKWLoc, |
| 10790 | TemplateTy TemplateIn, |
| 10791 | IdentifierInfo *TemplateII, |
| 10792 | SourceLocation TemplateIILoc, |
| 10793 | SourceLocation LAngleLoc, |
| 10794 | ASTTemplateArgsPtr TemplateArgsIn, |
| 10795 | SourceLocation RAngleLoc) { |
| 10796 | if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) |
| 10797 | Diag(TypenameLoc, |
| 10798 | getLangOpts().CPlusPlus11 ? |
| 10799 | diag::warn_cxx98_compat_typename_outside_of_template : |
| 10800 | diag::ext_typename_outside_of_template) |
| 10801 | << FixItHint::CreateRemoval(TypenameLoc); |
| 10802 | |
| 10803 | // Strangely, non-type results are not ignored by this lookup, so the |
| 10804 | // program is ill-formed if it finds an injected-class-name. |
| 10805 | if (TypenameLoc.isValid()) { |
| 10806 | auto *LookupRD = |
| 10807 | dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false)); |
| 10808 | if (LookupRD && LookupRD->getIdentifier() == TemplateII) { |
| 10809 | Diag(TemplateIILoc, |
| 10810 | diag::ext_out_of_line_qualified_id_type_names_constructor) |
| 10811 | << TemplateII << 0 /*injected-class-name used as template name*/ |
| 10812 | << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/); |
| 10813 | } |
| 10814 | } |
| 10815 | |
| 10816 | // Translate the parser's template argument list in our AST format. |
| 10817 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
| 10818 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
| 10819 | |
| 10820 | TemplateName Template = TemplateIn.get(); |
| 10821 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
| 10822 | // Construct a dependent template specialization type. |
| 10823 | assert(DTN && "dependent template has non-dependent name?")(static_cast <bool> (DTN && "dependent template has non-dependent name?" ) ? void (0) : __assert_fail ("DTN && \"dependent template has non-dependent name?\"" , "clang/lib/Sema/SemaTemplate.cpp", 10823, __extension__ __PRETTY_FUNCTION__ )); |
| 10824 | assert(DTN->getQualifier() == SS.getScopeRep())(static_cast <bool> (DTN->getQualifier() == SS.getScopeRep ()) ? void (0) : __assert_fail ("DTN->getQualifier() == SS.getScopeRep()" , "clang/lib/Sema/SemaTemplate.cpp", 10824, __extension__ __PRETTY_FUNCTION__ )); |
| 10825 | QualType T = Context.getDependentTemplateSpecializationType( |
| 10826 | ETK_Typename, DTN->getQualifier(), DTN->getIdentifier(), |
| 10827 | TemplateArgs.arguments()); |
| 10828 | |
| 10829 | // Create source-location information for this type. |
| 10830 | TypeLocBuilder Builder; |
| 10831 | DependentTemplateSpecializationTypeLoc SpecTL |
| 10832 | = Builder.push<DependentTemplateSpecializationTypeLoc>(T); |
| 10833 | SpecTL.setElaboratedKeywordLoc(TypenameLoc); |
| 10834 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 10835 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| 10836 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
| 10837 | SpecTL.setLAngleLoc(LAngleLoc); |
| 10838 | SpecTL.setRAngleLoc(RAngleLoc); |
| 10839 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
| 10840 | SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
| 10841 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
| 10842 | } |
| 10843 | |
| 10844 | QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); |
| 10845 | if (T.isNull()) |
| 10846 | return true; |
| 10847 | |
| 10848 | // Provide source-location information for the template specialization type. |
| 10849 | TypeLocBuilder Builder; |
| 10850 | TemplateSpecializationTypeLoc SpecTL |
| 10851 | = Builder.push<TemplateSpecializationTypeLoc>(T); |
| 10852 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| 10853 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
| 10854 | SpecTL.setLAngleLoc(LAngleLoc); |
| 10855 | SpecTL.setRAngleLoc(RAngleLoc); |
| 10856 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
| 10857 | SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
| 10858 | |
| 10859 | T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T); |
| 10860 | ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); |
| 10861 | TL.setElaboratedKeywordLoc(TypenameLoc); |
| 10862 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 10863 | |
| 10864 | TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); |
| 10865 | return CreateParsedType(T, TSI); |
| 10866 | } |
| 10867 | |
| 10868 | |
| 10869 | /// Determine whether this failed name lookup should be treated as being |
| 10870 | /// disabled by a usage of std::enable_if. |
| 10871 | static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, |
| 10872 | SourceRange &CondRange, Expr *&Cond) { |
| 10873 | // We must be looking for a ::type... |
| 10874 | if (!II.isStr("type")) |
| 10875 | return false; |
| 10876 | |
| 10877 | // ... within an explicitly-written template specialization... |
| 10878 | if (!NNS || !NNS.getNestedNameSpecifier()->getAsType()) |
| 10879 | return false; |
| 10880 | TypeLoc EnableIfTy = NNS.getTypeLoc(); |
| 10881 | TemplateSpecializationTypeLoc EnableIfTSTLoc = |
| 10882 | EnableIfTy.getAs<TemplateSpecializationTypeLoc>(); |
| 10883 | if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0) |
| 10884 | return false; |
| 10885 | const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr(); |
| 10886 | |
| 10887 | // ... which names a complete class template declaration... |
| 10888 | const TemplateDecl *EnableIfDecl = |
| 10889 | EnableIfTST->getTemplateName().getAsTemplateDecl(); |
| 10890 | if (!EnableIfDecl || EnableIfTST->isIncompleteType()) |
| 10891 | return false; |
| 10892 | |
| 10893 | // ... called "enable_if". |
| 10894 | const IdentifierInfo *EnableIfII = |
| 10895 | EnableIfDecl->getDeclName().getAsIdentifierInfo(); |
| 10896 | if (!EnableIfII || !EnableIfII->isStr("enable_if")) |
| 10897 | return false; |
| 10898 | |
| 10899 | // Assume the first template argument is the condition. |
| 10900 | CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange(); |
| 10901 | |
| 10902 | // Dig out the condition. |
| 10903 | Cond = nullptr; |
| 10904 | if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind() |
| 10905 | != TemplateArgument::Expression) |
| 10906 | return true; |
| 10907 | |
| 10908 | Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression(); |
| 10909 | |
| 10910 | // Ignore Boolean literals; they add no value. |
| 10911 | if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts())) |
| 10912 | Cond = nullptr; |
| 10913 | |
| 10914 | return true; |
| 10915 | } |
| 10916 | |
| 10917 | QualType |
| 10918 | Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, |
| 10919 | SourceLocation KeywordLoc, |
| 10920 | NestedNameSpecifierLoc QualifierLoc, |
| 10921 | const IdentifierInfo &II, |
| 10922 | SourceLocation IILoc, |
| 10923 | TypeSourceInfo **TSI, |
| 10924 | bool DeducedTSTContext) { |
| 10925 | QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc, |
| 10926 | DeducedTSTContext); |
| 10927 | if (T.isNull()) |
| 10928 | return QualType(); |
| 10929 | |
| 10930 | *TSI = Context.CreateTypeSourceInfo(T); |
| 10931 | if (isa<DependentNameType>(T)) { |
| 10932 | DependentNameTypeLoc TL = |
| 10933 | (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>(); |
| 10934 | TL.setElaboratedKeywordLoc(KeywordLoc); |
| 10935 | TL.setQualifierLoc(QualifierLoc); |
| 10936 | TL.setNameLoc(IILoc); |
| 10937 | } else { |
| 10938 | ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>(); |
| 10939 | TL.setElaboratedKeywordLoc(KeywordLoc); |
| 10940 | TL.setQualifierLoc(QualifierLoc); |
| 10941 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc); |
| 10942 | } |
| 10943 | return T; |
| 10944 | } |
| 10945 | |
| 10946 | /// Build the type that describes a C++ typename specifier, |
| 10947 | /// e.g., "typename T::type". |
| 10948 | QualType |
| 10949 | Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, |
| 10950 | SourceLocation KeywordLoc, |
| 10951 | NestedNameSpecifierLoc QualifierLoc, |
| 10952 | const IdentifierInfo &II, |
| 10953 | SourceLocation IILoc, bool DeducedTSTContext) { |
| 10954 | CXXScopeSpec SS; |
| 10955 | SS.Adopt(QualifierLoc); |
| 10956 | |
| 10957 | DeclContext *Ctx = nullptr; |
| 10958 | if (QualifierLoc) { |
| 10959 | Ctx = computeDeclContext(SS); |
| 10960 | if (!Ctx) { |
| 10961 | // If the nested-name-specifier is dependent and couldn't be |
| 10962 | // resolved to a type, build a typename type. |
| 10963 | assert(QualifierLoc.getNestedNameSpecifier()->isDependent())(static_cast <bool> (QualifierLoc.getNestedNameSpecifier ()->isDependent()) ? void (0) : __assert_fail ("QualifierLoc.getNestedNameSpecifier()->isDependent()" , "clang/lib/Sema/SemaTemplate.cpp", 10963, __extension__ __PRETTY_FUNCTION__ )); |
| 10964 | return Context.getDependentNameType(Keyword, |
| 10965 | QualifierLoc.getNestedNameSpecifier(), |
| 10966 | &II); |
| 10967 | } |
| 10968 | |
| 10969 | // If the nested-name-specifier refers to the current instantiation, |
| 10970 | // the "typename" keyword itself is superfluous. In C++03, the |
| 10971 | // program is actually ill-formed. However, DR 382 (in C++0x CD1) |
| 10972 | // allows such extraneous "typename" keywords, and we retroactively |
| 10973 | // apply this DR to C++03 code with only a warning. In any case we continue. |
| 10974 | |
| 10975 | if (RequireCompleteDeclContext(SS, Ctx)) |
| 10976 | return QualType(); |
| 10977 | } |
| 10978 | |
| 10979 | DeclarationName Name(&II); |
| 10980 | LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); |
| 10981 | if (Ctx) |
| 10982 | LookupQualifiedName(Result, Ctx, SS); |
| 10983 | else |
| 10984 | LookupName(Result, CurScope); |
| 10985 | unsigned DiagID = 0; |
| 10986 | Decl *Referenced = nullptr; |
| 10987 | switch (Result.getResultKind()) { |
| 10988 | case LookupResult::NotFound: { |
| 10989 | // If we're looking up 'type' within a template named 'enable_if', produce |
| 10990 | // a more specific diagnostic. |
| 10991 | SourceRange CondRange; |
| 10992 | Expr *Cond = nullptr; |
| 10993 | if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) { |
| 10994 | // If we have a condition, narrow it down to the specific failed |
| 10995 | // condition. |
| 10996 | if (Cond) { |
| 10997 | Expr *FailedCond; |
| 10998 | std::string FailedDescription; |
| 10999 | std::tie(FailedCond, FailedDescription) = |
| 11000 | findFailedBooleanCondition(Cond); |
| 11001 | |
| 11002 | Diag(FailedCond->getExprLoc(), |
| 11003 | diag::err_typename_nested_not_found_requirement) |
| 11004 | << FailedDescription |
| 11005 | << FailedCond->getSourceRange(); |
| 11006 | return QualType(); |
| 11007 | } |
| 11008 | |
| 11009 | Diag(CondRange.getBegin(), |
| 11010 | diag::err_typename_nested_not_found_enable_if) |
| 11011 | << Ctx << CondRange; |
| 11012 | return QualType(); |
| 11013 | } |
| 11014 | |
| 11015 | DiagID = Ctx ? diag::err_typename_nested_not_found |
| 11016 | : diag::err_unknown_typename; |
| 11017 | break; |
| 11018 | } |
| 11019 | |
| 11020 | case LookupResult::FoundUnresolvedValue: { |
| 11021 | // We found a using declaration that is a value. Most likely, the using |
| 11022 | // declaration itself is meant to have the 'typename' keyword. |
| 11023 | SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), |
| 11024 | IILoc); |
| 11025 | Diag(IILoc, diag::err_typename_refers_to_using_value_decl) |
| 11026 | << Name << Ctx << FullRange; |
| 11027 | if (UnresolvedUsingValueDecl *Using |
| 11028 | = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){ |
| 11029 | SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); |
| 11030 | Diag(Loc, diag::note_using_value_decl_missing_typename) |
| 11031 | << FixItHint::CreateInsertion(Loc, "typename "); |
| 11032 | } |
| 11033 | } |
| 11034 | // Fall through to create a dependent typename type, from which we can recover |
| 11035 | // better. |
| 11036 | [[fallthrough]]; |
| 11037 | |
| 11038 | case LookupResult::NotFoundInCurrentInstantiation: |
| 11039 | // Okay, it's a member of an unknown instantiation. |
| 11040 | return Context.getDependentNameType(Keyword, |
| 11041 | QualifierLoc.getNestedNameSpecifier(), |
| 11042 | &II); |
| 11043 | |
| 11044 | case LookupResult::Found: |
| 11045 | if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { |
| 11046 | // C++ [class.qual]p2: |
| 11047 | // In a lookup in which function names are not ignored and the |
| 11048 | // nested-name-specifier nominates a class C, if the name specified |
| 11049 | // after the nested-name-specifier, when looked up in C, is the |
| 11050 | // injected-class-name of C [...] then the name is instead considered |
| 11051 | // to name the constructor of class C. |
| 11052 | // |
| 11053 | // Unlike in an elaborated-type-specifier, function names are not ignored |
| 11054 | // in typename-specifier lookup. However, they are ignored in all the |
| 11055 | // contexts where we form a typename type with no keyword (that is, in |
| 11056 | // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers). |
| 11057 | // |
| 11058 | // FIXME: That's not strictly true: mem-initializer-id lookup does not |
| 11059 | // ignore functions, but that appears to be an oversight. |
| 11060 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx); |
| 11061 | auto *FoundRD = dyn_cast<CXXRecordDecl>(Type); |
| 11062 | if (Keyword == ETK_Typename && LookupRD && FoundRD && |
| 11063 | FoundRD->isInjectedClassName() && |
| 11064 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) |
| 11065 | Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor) |
| 11066 | << &II << 1 << 0 /*'typename' keyword used*/; |
| 11067 | |
| 11068 | // We found a type. Build an ElaboratedType, since the |
| 11069 | // typename-specifier was just sugar. |
| 11070 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); |
| 11071 | return Context.getElaboratedType(Keyword, |
| 11072 | QualifierLoc.getNestedNameSpecifier(), |
| 11073 | Context.getTypeDeclType(Type)); |
| 11074 | } |
| 11075 | |
| 11076 | // C++ [dcl.type.simple]p2: |
| 11077 | // A type-specifier of the form |
| 11078 | // typename[opt] nested-name-specifier[opt] template-name |
| 11079 | // is a placeholder for a deduced class type [...]. |
| 11080 | if (getLangOpts().CPlusPlus17) { |
| 11081 | if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) { |
| 11082 | if (!DeducedTSTContext) { |
| 11083 | QualType T(QualifierLoc |
| 11084 | ? QualifierLoc.getNestedNameSpecifier()->getAsType() |
| 11085 | : nullptr, 0); |
| 11086 | if (!T.isNull()) |
| 11087 | Diag(IILoc, diag::err_dependent_deduced_tst) |
| 11088 | << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T; |
| 11089 | else |
| 11090 | Diag(IILoc, diag::err_deduced_tst) |
| 11091 | << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)); |
| 11092 | Diag(TD->getLocation(), diag::note_template_decl_here); |
| 11093 | return QualType(); |
| 11094 | } |
| 11095 | return Context.getElaboratedType( |
| 11096 | Keyword, QualifierLoc.getNestedNameSpecifier(), |
| 11097 | Context.getDeducedTemplateSpecializationType(TemplateName(TD), |
| 11098 | QualType(), false)); |
| 11099 | } |
| 11100 | } |
| 11101 | |
| 11102 | DiagID = Ctx ? diag::err_typename_nested_not_type |
| 11103 | : diag::err_typename_not_type; |
| 11104 | Referenced = Result.getFoundDecl(); |
| 11105 | break; |
| 11106 | |
| 11107 | case LookupResult::FoundOverloaded: |
| 11108 | DiagID = Ctx ? diag::err_typename_nested_not_type |
| 11109 | : diag::err_typename_not_type; |
| 11110 | Referenced = *Result.begin(); |
| 11111 | break; |
| 11112 | |
| 11113 | case LookupResult::Ambiguous: |
| 11114 | return QualType(); |
| 11115 | } |
| 11116 | |
| 11117 | // If we get here, it's because name lookup did not find a |
| 11118 | // type. Emit an appropriate diagnostic and return an error. |
| 11119 | SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), |
| 11120 | IILoc); |
| 11121 | if (Ctx) |
| 11122 | Diag(IILoc, DiagID) << FullRange << Name << Ctx; |
| 11123 | else |
| 11124 | Diag(IILoc, DiagID) << FullRange << Name; |
| 11125 | if (Referenced) |
| 11126 | Diag(Referenced->getLocation(), |
| 11127 | Ctx ? diag::note_typename_member_refers_here |
| 11128 | : diag::note_typename_refers_here) |
| 11129 | << Name; |
| 11130 | return QualType(); |
| 11131 | } |
| 11132 | |
| 11133 | namespace { |
| 11134 | // See Sema::RebuildTypeInCurrentInstantiation |
| 11135 | class CurrentInstantiationRebuilder |
| 11136 | : public TreeTransform<CurrentInstantiationRebuilder> { |
| 11137 | SourceLocation Loc; |
| 11138 | DeclarationName Entity; |
| 11139 | |
| 11140 | public: |
| 11141 | typedef TreeTransform<CurrentInstantiationRebuilder> inherited; |
| 11142 | |
| 11143 | CurrentInstantiationRebuilder(Sema &SemaRef, |
| 11144 | SourceLocation Loc, |
| 11145 | DeclarationName Entity) |
| 11146 | : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), |
| 11147 | Loc(Loc), Entity(Entity) { } |
| 11148 | |
| 11149 | /// Determine whether the given type \p T has already been |
| 11150 | /// transformed. |
| 11151 | /// |
| 11152 | /// For the purposes of type reconstruction, a type has already been |
| 11153 | /// transformed if it is NULL or if it is not dependent. |
| 11154 | bool AlreadyTransformed(QualType T) { |
| 11155 | return T.isNull() || !T->isInstantiationDependentType(); |
| 11156 | } |
| 11157 | |
| 11158 | /// Returns the location of the entity whose type is being |
| 11159 | /// rebuilt. |
| 11160 | SourceLocation getBaseLocation() { return Loc; } |
| 11161 | |
| 11162 | /// Returns the name of the entity whose type is being rebuilt. |
| 11163 | DeclarationName getBaseEntity() { return Entity; } |
| 11164 | |
| 11165 | /// Sets the "base" location and entity when that |
| 11166 | /// information is known based on another transformation. |
| 11167 | void setBase(SourceLocation Loc, DeclarationName Entity) { |
| 11168 | this->Loc = Loc; |
| 11169 | this->Entity = Entity; |
| 11170 | } |
| 11171 | |
| 11172 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
| 11173 | // Lambdas never need to be transformed. |
| 11174 | return E; |
| 11175 | } |
| 11176 | }; |
| 11177 | } // end anonymous namespace |
| 11178 | |
| 11179 | /// Rebuilds a type within the context of the current instantiation. |
| 11180 | /// |
| 11181 | /// The type \p T is part of the type of an out-of-line member definition of |
| 11182 | /// a class template (or class template partial specialization) that was parsed |
| 11183 | /// and constructed before we entered the scope of the class template (or |
| 11184 | /// partial specialization thereof). This routine will rebuild that type now |
| 11185 | /// that we have entered the declarator's scope, which may produce different |
| 11186 | /// canonical types, e.g., |
| 11187 | /// |
| 11188 | /// \code |
| 11189 | /// template<typename T> |
| 11190 | /// struct X { |
| 11191 | /// typedef T* pointer; |
| 11192 | /// pointer data(); |
| 11193 | /// }; |
| 11194 | /// |
| 11195 | /// template<typename T> |
| 11196 | /// typename X<T>::pointer X<T>::data() { ... } |
| 11197 | /// \endcode |
| 11198 | /// |
| 11199 | /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, |
| 11200 | /// since we do not know that we can look into X<T> when we parsed the type. |
| 11201 | /// This function will rebuild the type, performing the lookup of "pointer" |
| 11202 | /// in X<T> and returning an ElaboratedType whose canonical type is the same |
| 11203 | /// as the canonical type of T*, allowing the return types of the out-of-line |
| 11204 | /// definition and the declaration to match. |
| 11205 | TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, |
| 11206 | SourceLocation Loc, |
| 11207 | DeclarationName Name) { |
| 11208 | if (!T || !T->getType()->isInstantiationDependentType()) |
| 11209 | return T; |
| 11210 | |
| 11211 | CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); |
| 11212 | return Rebuilder.TransformType(T); |
| 11213 | } |
| 11214 | |
| 11215 | ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { |
| 11216 | CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), |
| 11217 | DeclarationName()); |
| 11218 | return Rebuilder.TransformExpr(E); |
| 11219 | } |
| 11220 | |
| 11221 | bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { |
| 11222 | if (SS.isInvalid()) |
| 11223 | return true; |
| 11224 | |
| 11225 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
| 11226 | CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), |
| 11227 | DeclarationName()); |
| 11228 | NestedNameSpecifierLoc Rebuilt |
| 11229 | = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); |
| 11230 | if (!Rebuilt) |
| 11231 | return true; |
| 11232 | |
| 11233 | SS.Adopt(Rebuilt); |
| 11234 | return false; |
| 11235 | } |
| 11236 | |
| 11237 | /// Rebuild the template parameters now that we know we're in a current |
| 11238 | /// instantiation. |
| 11239 | bool Sema::RebuildTemplateParamsInCurrentInstantiation( |
| 11240 | TemplateParameterList *Params) { |
| 11241 | for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
| 11242 | Decl *Param = Params->getParam(I); |
| 11243 | |
| 11244 | // There is nothing to rebuild in a type parameter. |
| 11245 | if (isa<TemplateTypeParmDecl>(Param)) |
| 11246 | continue; |
| 11247 | |
| 11248 | // Rebuild the template parameter list of a template template parameter. |
| 11249 | if (TemplateTemplateParmDecl *TTP |
| 11250 | = dyn_cast<TemplateTemplateParmDecl>(Param)) { |
| 11251 | if (RebuildTemplateParamsInCurrentInstantiation( |
| 11252 | TTP->getTemplateParameters())) |
| 11253 | return true; |
| 11254 | |
| 11255 | continue; |
| 11256 | } |
| 11257 | |
| 11258 | // Rebuild the type of a non-type template parameter. |
| 11259 | NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param); |
| 11260 | TypeSourceInfo *NewTSI |
| 11261 | = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(), |
| 11262 | NTTP->getLocation(), |
| 11263 | NTTP->getDeclName()); |
| 11264 | if (!NewTSI) |
| 11265 | return true; |
| 11266 | |
| 11267 | if (NewTSI->getType()->isUndeducedType()) { |
| 11268 | // C++17 [temp.dep.expr]p3: |
| 11269 | // An id-expression is type-dependent if it contains |
| 11270 | // - an identifier associated by name lookup with a non-type |
| 11271 | // template-parameter declared with a type that contains a |
| 11272 | // placeholder type (7.1.7.4), |
| 11273 | NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI); |
| 11274 | } |
| 11275 | |
| 11276 | if (NewTSI != NTTP->getTypeSourceInfo()) { |
| 11277 | NTTP->setTypeSourceInfo(NewTSI); |
| 11278 | NTTP->setType(NewTSI->getType()); |
| 11279 | } |
| 11280 | } |
| 11281 | |
| 11282 | return false; |
| 11283 | } |
| 11284 | |
| 11285 | /// Produces a formatted string that describes the binding of |
| 11286 | /// template parameters to template arguments. |
| 11287 | std::string |
| 11288 | Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
| 11289 | const TemplateArgumentList &Args) { |
| 11290 | return getTemplateArgumentBindingsText(Params, Args.data(), Args.size()); |
| 11291 | } |
| 11292 | |
| 11293 | std::string |
| 11294 | Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
| 11295 | const TemplateArgument *Args, |
| 11296 | unsigned NumArgs) { |
| 11297 | SmallString<128> Str; |
| 11298 | llvm::raw_svector_ostream Out(Str); |
| 11299 | |
| 11300 | if (!Params || Params->size() == 0 || NumArgs == 0) |
| 11301 | return std::string(); |
| 11302 | |
| 11303 | for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
| 11304 | if (I >= NumArgs) |
| 11305 | break; |
| 11306 | |
| 11307 | if (I == 0) |
| 11308 | Out << "[with "; |
| 11309 | else |
| 11310 | Out << ", "; |
| 11311 | |
| 11312 | if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { |
| 11313 | Out << Id->getName(); |
| 11314 | } else { |
| 11315 | Out << '$' << I; |
| 11316 | } |
| 11317 | |
| 11318 | Out << " = "; |
| 11319 | Args[I].print(getPrintingPolicy(), Out, |
| 11320 | TemplateParameterList::shouldIncludeTypeForArgument( |
| 11321 | getPrintingPolicy(), Params, I)); |
| 11322 | } |
| 11323 | |
| 11324 | Out << ']'; |
| 11325 | return std::string(Out.str()); |
| 11326 | } |
| 11327 | |
| 11328 | void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, |
| 11329 | CachedTokens &Toks) { |
| 11330 | if (!FD) |
| 11331 | return; |
| 11332 | |
| 11333 | auto LPT = std::make_unique<LateParsedTemplate>(); |
| 11334 | |
| 11335 | // Take tokens to avoid allocations |
| 11336 | LPT->Toks.swap(Toks); |
| 11337 | LPT->D = FnD; |
| 11338 | LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT))); |
| 11339 | |
| 11340 | FD->setLateTemplateParsed(true); |
| 11341 | } |
| 11342 | |
| 11343 | void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) { |
| 11344 | if (!FD) |
| 11345 | return; |
| 11346 | FD->setLateTemplateParsed(false); |
| 11347 | } |
| 11348 | |
| 11349 | bool Sema::IsInsideALocalClassWithinATemplateFunction() { |
| 11350 | DeclContext *DC = CurContext; |
| 11351 | |
| 11352 | while (DC) { |
| 11353 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { |
| 11354 | const FunctionDecl *FD = RD->isLocalClass(); |
| 11355 | return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate); |
| 11356 | } else if (DC->isTranslationUnit() || DC->isNamespace()) |
| 11357 | return false; |
| 11358 | |
| 11359 | DC = DC->getParent(); |
| 11360 | } |
| 11361 | return false; |
| 11362 | } |
| 11363 | |
| 11364 | namespace { |
| 11365 | /// Walk the path from which a declaration was instantiated, and check |
| 11366 | /// that every explicit specialization along that path is visible. This enforces |
| 11367 | /// C++ [temp.expl.spec]/6: |
| 11368 | /// |
| 11369 | /// If a template, a member template or a member of a class template is |
| 11370 | /// explicitly specialized then that specialization shall be declared before |
| 11371 | /// the first use of that specialization that would cause an implicit |
| 11372 | /// instantiation to take place, in every translation unit in which such a |
| 11373 | /// use occurs; no diagnostic is required. |
| 11374 | /// |
| 11375 | /// and also C++ [temp.class.spec]/1: |
| 11376 | /// |
| 11377 | /// A partial specialization shall be declared before the first use of a |
| 11378 | /// class template specialization that would make use of the partial |
| 11379 | /// specialization as the result of an implicit or explicit instantiation |
| 11380 | /// in every translation unit in which such a use occurs; no diagnostic is |
| 11381 | /// required. |
| 11382 | class ExplicitSpecializationVisibilityChecker { |
| 11383 | Sema &S; |
| 11384 | SourceLocation Loc; |
| 11385 | llvm::SmallVector<Module *, 8> Modules; |
| 11386 | Sema::AcceptableKind Kind; |
| 11387 | |
| 11388 | public: |
| 11389 | ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc, |
| 11390 | Sema::AcceptableKind Kind) |
| 11391 | : S(S), Loc(Loc), Kind(Kind) {} |
| 11392 | |
| 11393 | void check(NamedDecl *ND) { |
| 11394 | if (auto *FD = dyn_cast<FunctionDecl>(ND)) |
| 11395 | return checkImpl(FD); |
| 11396 | if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) |
| 11397 | return checkImpl(RD); |
| 11398 | if (auto *VD = dyn_cast<VarDecl>(ND)) |
| 11399 | return checkImpl(VD); |
| 11400 | if (auto *ED = dyn_cast<EnumDecl>(ND)) |
| 11401 | return checkImpl(ED); |
| 11402 | } |
| 11403 | |
| 11404 | private: |
| 11405 | void diagnose(NamedDecl *D, bool IsPartialSpec) { |
| 11406 | auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization |
| 11407 | : Sema::MissingImportKind::ExplicitSpecialization; |
| 11408 | const bool Recover = true; |
| 11409 | |
| 11410 | // If we got a custom set of modules (because only a subset of the |
| 11411 | // declarations are interesting), use them, otherwise let |
| 11412 | // diagnoseMissingImport intelligently pick some. |
| 11413 | if (Modules.empty()) |
| 11414 | S.diagnoseMissingImport(Loc, D, Kind, Recover); |
| 11415 | else |
| 11416 | S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover); |
| 11417 | } |
| 11418 | |
| 11419 | bool CheckMemberSpecialization(const NamedDecl *D) { |
| 11420 | return Kind == Sema::AcceptableKind::Visible |
| 11421 | ? S.hasVisibleMemberSpecialization(D) |
| 11422 | : S.hasReachableMemberSpecialization(D); |
| 11423 | } |
| 11424 | |
| 11425 | bool CheckExplicitSpecialization(const NamedDecl *D) { |
| 11426 | return Kind == Sema::AcceptableKind::Visible |
| 11427 | ? S.hasVisibleExplicitSpecialization(D) |
| 11428 | : S.hasReachableExplicitSpecialization(D); |
| 11429 | } |
| 11430 | |
| 11431 | bool CheckDeclaration(const NamedDecl *D) { |
| 11432 | return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D) |
| 11433 | : S.hasReachableDeclaration(D); |
| 11434 | } |
| 11435 | |
| 11436 | // Check a specific declaration. There are three problematic cases: |
| 11437 | // |
| 11438 | // 1) The declaration is an explicit specialization of a template |
| 11439 | // specialization. |
| 11440 | // 2) The declaration is an explicit specialization of a member of an |
| 11441 | // templated class. |
| 11442 | // 3) The declaration is an instantiation of a template, and that template |
| 11443 | // is an explicit specialization of a member of a templated class. |
| 11444 | // |
| 11445 | // We don't need to go any deeper than that, as the instantiation of the |
| 11446 | // surrounding class / etc is not triggered by whatever triggered this |
| 11447 | // instantiation, and thus should be checked elsewhere. |
| 11448 | template<typename SpecDecl> |
| 11449 | void checkImpl(SpecDecl *Spec) { |
| 11450 | bool IsHiddenExplicitSpecialization = false; |
| 11451 | if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { |
| 11452 | IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo() |
| 11453 | ? !CheckMemberSpecialization(Spec) |
| 11454 | : !CheckExplicitSpecialization(Spec); |
| 11455 | } else { |
| 11456 | checkInstantiated(Spec); |
| 11457 | } |
| 11458 | |
| 11459 | if (IsHiddenExplicitSpecialization) |
| 11460 | diagnose(Spec->getMostRecentDecl(), false); |
| 11461 | } |
| 11462 | |
| 11463 | void checkInstantiated(FunctionDecl *FD) { |
| 11464 | if (auto *TD = FD->getPrimaryTemplate()) |
| 11465 | checkTemplate(TD); |
| 11466 | } |
| 11467 | |
| 11468 | void checkInstantiated(CXXRecordDecl *RD) { |
| 11469 | auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD); |
| 11470 | if (!SD) |
| 11471 | return; |
| 11472 | |
| 11473 | auto From = SD->getSpecializedTemplateOrPartial(); |
| 11474 | if (auto *TD = From.dyn_cast<ClassTemplateDecl *>()) |
| 11475 | checkTemplate(TD); |
| 11476 | else if (auto *TD = |
| 11477 | From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { |
| 11478 | if (!CheckDeclaration(TD)) |
| 11479 | diagnose(TD, true); |
| 11480 | checkTemplate(TD); |
| 11481 | } |
| 11482 | } |
| 11483 | |
| 11484 | void checkInstantiated(VarDecl *RD) { |
| 11485 | auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD); |
| 11486 | if (!SD) |
| 11487 | return; |
| 11488 | |
| 11489 | auto From = SD->getSpecializedTemplateOrPartial(); |
| 11490 | if (auto *TD = From.dyn_cast<VarTemplateDecl *>()) |
| 11491 | checkTemplate(TD); |
| 11492 | else if (auto *TD = |
| 11493 | From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { |
| 11494 | if (!CheckDeclaration(TD)) |
| 11495 | diagnose(TD, true); |
| 11496 | checkTemplate(TD); |
| 11497 | } |
| 11498 | } |
| 11499 | |
| 11500 | void checkInstantiated(EnumDecl *FD) {} |
| 11501 | |
| 11502 | template<typename TemplDecl> |
| 11503 | void checkTemplate(TemplDecl *TD) { |
| 11504 | if (TD->isMemberSpecialization()) { |
| 11505 | if (!CheckMemberSpecialization(TD)) |
| 11506 | diagnose(TD->getMostRecentDecl(), false); |
| 11507 | } |
| 11508 | } |
| 11509 | }; |
| 11510 | } // end anonymous namespace |
| 11511 | |
| 11512 | void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) { |
| 11513 | if (!getLangOpts().Modules) |
| 11514 | return; |
| 11515 | |
| 11516 | ExplicitSpecializationVisibilityChecker(*this, Loc, |
| 11517 | Sema::AcceptableKind::Visible) |
| 11518 | .check(Spec); |
| 11519 | } |
| 11520 | |
| 11521 | void Sema::checkSpecializationReachability(SourceLocation Loc, |
| 11522 | NamedDecl *Spec) { |
| 11523 | if (!getLangOpts().CPlusPlusModules) |
| 11524 | return checkSpecializationVisibility(Loc, Spec); |
| 11525 | |
| 11526 | ExplicitSpecializationVisibilityChecker(*this, Loc, |
| 11527 | Sema::AcceptableKind::Reachable) |
| 11528 | .check(Spec); |
| 11529 | } |