| 1 | //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ |
| 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 C++ template instantiation. |
| 9 | // |
| 10 | //===----------------------------------------------------------------------===/ |
| 11 | |
| 12 | #include "TreeTransform.h" |
| 13 | #include "clang/AST/ASTConsumer.h" |
| 14 | #include "clang/AST/ASTContext.h" |
| 15 | #include "clang/AST/ASTLambda.h" |
| 16 | #include "clang/AST/ASTMutationListener.h" |
| 17 | #include "clang/AST/DeclBase.h" |
| 18 | #include "clang/AST/DeclTemplate.h" |
| 19 | #include "clang/AST/DynamicRecursiveASTVisitor.h" |
| 20 | #include "clang/AST/Expr.h" |
| 21 | #include "clang/AST/ExprConcepts.h" |
| 22 | #include "clang/AST/PrettyDeclStackTrace.h" |
| 23 | #include "clang/AST/Type.h" |
| 24 | #include "clang/AST/TypeLoc.h" |
| 25 | #include "clang/AST/TypeVisitor.h" |
| 26 | #include "clang/Basic/LangOptions.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/Sema.h" |
| 32 | #include "clang/Sema/SemaConcept.h" |
| 33 | #include "clang/Sema/SemaInternal.h" |
| 34 | #include "clang/Sema/Template.h" |
| 35 | #include "clang/Sema/TemplateDeduction.h" |
| 36 | #include "llvm/ADT/SmallVectorExtras.h" |
| 37 | #include "llvm/ADT/StringExtras.h" |
| 38 | #include "llvm/Support/ErrorHandling.h" |
| 39 | #include "llvm/Support/SaveAndRestore.h" |
| 40 | #include "llvm/Support/TimeProfiler.h" |
| 41 | #include <optional> |
| 42 | |
| 43 | using namespace clang; |
| 44 | using namespace sema; |
| 45 | |
| 46 | //===----------------------------------------------------------------------===/ |
| 47 | // Template Instantiation Support |
| 48 | //===----------------------------------------------------------------------===/ |
| 49 | |
| 50 | namespace { |
| 51 | namespace TemplateInstArgsHelpers { |
| 52 | struct Response { |
| 53 | const Decl *NextDecl = nullptr; |
| 54 | bool IsDone = false; |
| 55 | bool ClearRelativeToPrimary = true; |
| 56 | static Response Done() { |
| 57 | Response R; |
| 58 | R.IsDone = true; |
| 59 | return R; |
| 60 | } |
| 61 | static Response ChangeDecl(const Decl *ND) { |
| 62 | Response R; |
| 63 | R.NextDecl = ND; |
| 64 | return R; |
| 65 | } |
| 66 | static Response ChangeDecl(const DeclContext *Ctx) { |
| 67 | Response R; |
| 68 | R.NextDecl = Decl::castFromDeclContext(Ctx); |
| 69 | return R; |
| 70 | } |
| 71 | |
| 72 | static Response UseNextDecl(const Decl *CurDecl) { |
| 73 | return ChangeDecl(Ctx: CurDecl->getDeclContext()); |
| 74 | } |
| 75 | |
| 76 | static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) { |
| 77 | Response R = Response::UseNextDecl(CurDecl); |
| 78 | R.ClearRelativeToPrimary = false; |
| 79 | return R; |
| 80 | } |
| 81 | }; |
| 82 | |
| 83 | // Retrieve the primary template for a lambda call operator. It's |
| 84 | // unfortunate that we only have the mappings of call operators rather |
| 85 | // than lambda classes. |
| 86 | const FunctionDecl * |
| 87 | getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) { |
| 88 | if (!isLambdaCallOperator(DC: LambdaCallOperator)) |
| 89 | return LambdaCallOperator; |
| 90 | while (true) { |
| 91 | if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>( |
| 92 | Val: LambdaCallOperator->getDescribedTemplate()); |
| 93 | FTD && FTD->getInstantiatedFromMemberTemplate()) { |
| 94 | LambdaCallOperator = |
| 95 | FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl(); |
| 96 | } else if (LambdaCallOperator->getPrimaryTemplate()) { |
| 97 | // Cases where the lambda operator is instantiated in |
| 98 | // TemplateDeclInstantiator::VisitCXXMethodDecl. |
| 99 | LambdaCallOperator = |
| 100 | LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl(); |
| 101 | } else if (auto *Prev = cast<CXXMethodDecl>(Val: LambdaCallOperator) |
| 102 | ->getInstantiatedFromMemberFunction()) |
| 103 | LambdaCallOperator = Prev; |
| 104 | else |
| 105 | break; |
| 106 | } |
| 107 | return LambdaCallOperator; |
| 108 | } |
| 109 | |
| 110 | struct EnclosingTypeAliasTemplateDetails { |
| 111 | TypeAliasTemplateDecl *Template = nullptr; |
| 112 | TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr; |
| 113 | ArrayRef<TemplateArgument> AssociatedTemplateArguments; |
| 114 | |
| 115 | explicit operator bool() noexcept { return Template; } |
| 116 | }; |
| 117 | |
| 118 | // Find the enclosing type alias template Decl from CodeSynthesisContexts, as |
| 119 | // well as its primary template and instantiating template arguments. |
| 120 | EnclosingTypeAliasTemplateDetails |
| 121 | getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) { |
| 122 | for (auto &CSC : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) { |
| 123 | if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind:: |
| 124 | TypeAliasTemplateInstantiation) |
| 125 | continue; |
| 126 | EnclosingTypeAliasTemplateDetails Result; |
| 127 | auto *TATD = cast<TypeAliasTemplateDecl>(Val: CSC.Entity), |
| 128 | *Next = TATD->getInstantiatedFromMemberTemplate(); |
| 129 | Result = { |
| 130 | /*Template=*/TATD, |
| 131 | /*PrimaryTypeAliasDecl=*/TATD, |
| 132 | /*AssociatedTemplateArguments=*/CSC.template_arguments(), |
| 133 | }; |
| 134 | while (Next) { |
| 135 | Result.PrimaryTypeAliasDecl = Next; |
| 136 | Next = Next->getInstantiatedFromMemberTemplate(); |
| 137 | } |
| 138 | return Result; |
| 139 | } |
| 140 | return {}; |
| 141 | } |
| 142 | |
| 143 | // Check if we are currently inside of a lambda expression that is |
| 144 | // surrounded by a using alias declaration. e.g. |
| 145 | // template <class> using type = decltype([](auto) { ^ }()); |
| 146 | // We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never |
| 147 | // a DeclContext, nor does it have an associated specialization Decl from which |
| 148 | // we could collect these template arguments. |
| 149 | bool isLambdaEnclosedByTypeAliasDecl( |
| 150 | const FunctionDecl *LambdaCallOperator, |
| 151 | const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) { |
| 152 | struct Visitor : DynamicRecursiveASTVisitor { |
| 153 | Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {} |
| 154 | bool VisitLambdaExpr(LambdaExpr *LE) override { |
| 155 | // Return true to bail out of the traversal, implying the Decl contains |
| 156 | // the lambda. |
| 157 | return getPrimaryTemplateOfGenericLambda(LambdaCallOperator: LE->getCallOperator()) != |
| 158 | CallOperator; |
| 159 | } |
| 160 | const FunctionDecl *CallOperator; |
| 161 | }; |
| 162 | |
| 163 | QualType Underlying = |
| 164 | PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType(); |
| 165 | |
| 166 | return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator)) |
| 167 | .TraverseType(T: Underlying); |
| 168 | } |
| 169 | |
| 170 | // Add template arguments from a variable template instantiation. |
| 171 | Response |
| 172 | HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec, |
| 173 | MultiLevelTemplateArgumentList &Result, |
| 174 | bool SkipForSpecialization) { |
| 175 | // For a class-scope explicit specialization, there are no template arguments |
| 176 | // at this level, but there may be enclosing template arguments. |
| 177 | if (VarTemplSpec->isClassScopeExplicitSpecialization()) |
| 178 | return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec); |
| 179 | |
| 180 | // We're done when we hit an explicit specialization. |
| 181 | if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && |
| 182 | !isa<VarTemplatePartialSpecializationDecl>(Val: VarTemplSpec)) |
| 183 | return Response::Done(); |
| 184 | |
| 185 | // If this variable template specialization was instantiated from a |
| 186 | // specialized member that is a variable template, we're done. |
| 187 | assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?" ); |
| 188 | llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *> |
| 189 | Specialized = VarTemplSpec->getSpecializedTemplateOrPartial(); |
| 190 | if (VarTemplatePartialSpecializationDecl *Partial = |
| 191 | dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: Specialized)) { |
| 192 | if (!SkipForSpecialization) |
| 193 | Result.addOuterTemplateArguments( |
| 194 | AssociatedDecl: Partial, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(), |
| 195 | /*Final=*/false); |
| 196 | if (Partial->isMemberSpecialization()) |
| 197 | return Response::Done(); |
| 198 | } else { |
| 199 | VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Val&: Specialized); |
| 200 | if (!SkipForSpecialization) |
| 201 | Result.addOuterTemplateArguments( |
| 202 | AssociatedDecl: Tmpl, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(), |
| 203 | /*Final=*/false); |
| 204 | if (Tmpl->isMemberSpecialization()) |
| 205 | return Response::Done(); |
| 206 | } |
| 207 | return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec); |
| 208 | } |
| 209 | |
| 210 | // If we have a template template parameter with translation unit context, |
| 211 | // then we're performing substitution into a default template argument of |
| 212 | // this template template parameter before we've constructed the template |
| 213 | // that will own this template template parameter. In this case, we |
| 214 | // use empty template parameter lists for all of the outer templates |
| 215 | // to avoid performing any substitutions. |
| 216 | Response |
| 217 | HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP, |
| 218 | MultiLevelTemplateArgumentList &Result) { |
| 219 | for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) |
| 220 | Result.addOuterTemplateArguments(std::nullopt); |
| 221 | return Response::Done(); |
| 222 | } |
| 223 | |
| 224 | Response HandlePartialClassTemplateSpec( |
| 225 | const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec, |
| 226 | MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) { |
| 227 | if (!SkipForSpecialization) |
| 228 | Result.addOuterRetainedLevels(Num: PartialClassTemplSpec->getTemplateDepth()); |
| 229 | return Response::Done(); |
| 230 | } |
| 231 | |
| 232 | // Add template arguments from a class template instantiation. |
| 233 | Response |
| 234 | HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec, |
| 235 | MultiLevelTemplateArgumentList &Result, |
| 236 | bool SkipForSpecialization) { |
| 237 | if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) { |
| 238 | // We're done when we hit an explicit specialization. |
| 239 | if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && |
| 240 | !isa<ClassTemplatePartialSpecializationDecl>(Val: ClassTemplSpec)) |
| 241 | return Response::Done(); |
| 242 | |
| 243 | if (!SkipForSpecialization) |
| 244 | Result.addOuterTemplateArguments( |
| 245 | AssociatedDecl: const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec), |
| 246 | Args: ClassTemplSpec->getTemplateInstantiationArgs().asArray(), |
| 247 | /*Final=*/false); |
| 248 | |
| 249 | // If this class template specialization was instantiated from a |
| 250 | // specialized member that is a class template, we're done. |
| 251 | assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?" ); |
| 252 | if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization()) |
| 253 | return Response::Done(); |
| 254 | |
| 255 | // If this was instantiated from a partial template specialization, we need |
| 256 | // to get the next level of declaration context from the partial |
| 257 | // specialization, as the ClassTemplateSpecializationDecl's |
| 258 | // DeclContext/LexicalDeclContext will be for the primary template. |
| 259 | if (auto *InstFromPartialTempl = |
| 260 | ClassTemplSpec->getSpecializedTemplateOrPartial() |
| 261 | .dyn_cast<ClassTemplatePartialSpecializationDecl *>()) |
| 262 | return Response::ChangeDecl( |
| 263 | Ctx: InstFromPartialTempl->getLexicalDeclContext()); |
| 264 | } |
| 265 | return Response::UseNextDecl(CurDecl: ClassTemplSpec); |
| 266 | } |
| 267 | |
| 268 | Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function, |
| 269 | MultiLevelTemplateArgumentList &Result, |
| 270 | const FunctionDecl *Pattern, bool RelativeToPrimary, |
| 271 | bool ForConstraintInstantiation, |
| 272 | bool ForDefaultArgumentSubstitution) { |
| 273 | // Add template arguments from a function template specialization. |
| 274 | if (!RelativeToPrimary && |
| 275 | Function->getTemplateSpecializationKindForInstantiation() == |
| 276 | TSK_ExplicitSpecialization) |
| 277 | return Response::Done(); |
| 278 | |
| 279 | if (!RelativeToPrimary && |
| 280 | Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { |
| 281 | // This is an implicit instantiation of an explicit specialization. We |
| 282 | // don't get any template arguments from this function but might get |
| 283 | // some from an enclosing template. |
| 284 | return Response::UseNextDecl(CurDecl: Function); |
| 285 | } else if (const TemplateArgumentList *TemplateArgs = |
| 286 | Function->getTemplateSpecializationArgs()) { |
| 287 | // Add the template arguments for this specialization. |
| 288 | Result.addOuterTemplateArguments(AssociatedDecl: const_cast<FunctionDecl *>(Function), |
| 289 | Args: TemplateArgs->asArray(), |
| 290 | /*Final=*/false); |
| 291 | |
| 292 | if (RelativeToPrimary && |
| 293 | (Function->getTemplateSpecializationKind() == |
| 294 | TSK_ExplicitSpecialization || |
| 295 | (Function->getFriendObjectKind() && |
| 296 | !Function->getPrimaryTemplate()->getFriendObjectKind()))) |
| 297 | return Response::UseNextDecl(CurDecl: Function); |
| 298 | |
| 299 | // If this function was instantiated from a specialized member that is |
| 300 | // a function template, we're done. |
| 301 | assert(Function->getPrimaryTemplate() && "No function template?" ); |
| 302 | if (!ForDefaultArgumentSubstitution && |
| 303 | Function->getPrimaryTemplate()->isMemberSpecialization()) |
| 304 | return Response::Done(); |
| 305 | |
| 306 | // If this function is a generic lambda specialization, we are done. |
| 307 | if (!ForConstraintInstantiation && |
| 308 | isGenericLambdaCallOperatorOrStaticInvokerSpecialization(DC: Function)) |
| 309 | return Response::Done(); |
| 310 | |
| 311 | } else if (auto *Template = Function->getDescribedFunctionTemplate()) { |
| 312 | assert( |
| 313 | (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && |
| 314 | "Outer template not instantiated?" ); |
| 315 | if (ForConstraintInstantiation) { |
| 316 | for (auto &Inst : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) { |
| 317 | if (Inst.Kind == Sema::CodeSynthesisContext::ConstraintsCheck && |
| 318 | Inst.Entity == Template) { |
| 319 | // After CWG2369, the outer templates are not instantiated when |
| 320 | // checking its associated constraints. So add them back through the |
| 321 | // synthesis context; this is useful for e.g. nested constraints |
| 322 | // involving lambdas. |
| 323 | Result.addOuterTemplateArguments(AssociatedDecl: Template, Args: Inst.template_arguments(), |
| 324 | /*Final=*/false); |
| 325 | break; |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | // If this is a friend or local declaration and it declares an entity at |
| 331 | // namespace scope, take arguments from its lexical parent |
| 332 | // instead of its semantic parent, unless of course the pattern we're |
| 333 | // instantiating actually comes from the file's context! |
| 334 | if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) && |
| 335 | Function->getNonTransparentDeclContext()->isFileContext() && |
| 336 | (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) { |
| 337 | return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext()); |
| 338 | } |
| 339 | |
| 340 | if (ForConstraintInstantiation && Function->getFriendObjectKind()) |
| 341 | return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext()); |
| 342 | return Response::UseNextDecl(CurDecl: Function); |
| 343 | } |
| 344 | |
| 345 | Response HandleFunctionTemplateDecl(Sema &SemaRef, |
| 346 | const FunctionTemplateDecl *FTD, |
| 347 | MultiLevelTemplateArgumentList &Result) { |
| 348 | if (!isa<ClassTemplateSpecializationDecl>(Val: FTD->getDeclContext())) { |
| 349 | Result.addOuterTemplateArguments( |
| 350 | AssociatedDecl: const_cast<FunctionTemplateDecl *>(FTD), |
| 351 | Args: const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs( |
| 352 | Context: SemaRef.Context), |
| 353 | /*Final=*/false); |
| 354 | |
| 355 | NestedNameSpecifier NNS = FTD->getTemplatedDecl()->getQualifier(); |
| 356 | |
| 357 | for (const Type *Ty = NNS.getKind() == NestedNameSpecifier::Kind::Type |
| 358 | ? NNS.getAsType() |
| 359 | : nullptr, |
| 360 | *NextTy = nullptr; |
| 361 | Ty && Ty->isInstantiationDependentType(); |
| 362 | Ty = std::exchange(obj&: NextTy, new_val: nullptr)) { |
| 363 | if (NestedNameSpecifier P = Ty->getPrefix(); |
| 364 | P.getKind() == NestedNameSpecifier::Kind::Type) |
| 365 | NextTy = P.getAsType(); |
| 366 | const auto *TSTy = dyn_cast<TemplateSpecializationType>(Val: Ty); |
| 367 | if (!TSTy) |
| 368 | continue; |
| 369 | |
| 370 | ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments(); |
| 371 | // Prefer template arguments from the injected-class-type if possible. |
| 372 | // For example, |
| 373 | // ```cpp |
| 374 | // template <class... Pack> struct S { |
| 375 | // template <class T> void foo(); |
| 376 | // }; |
| 377 | // template <class... Pack> template <class T> |
| 378 | // ^^^^^^^^^^^^^ InjectedTemplateArgs |
| 379 | // They're of kind TemplateArgument::Pack, not of |
| 380 | // TemplateArgument::Type. |
| 381 | // void S<Pack...>::foo() {} |
| 382 | // ^^^^^^^ |
| 383 | // TSTy->template_arguments() (which are of PackExpansionType) |
| 384 | // ``` |
| 385 | // This meets the contract in |
| 386 | // TreeTransform::TryExpandParameterPacks that the template arguments |
| 387 | // for unexpanded parameters should be of a Pack kind. |
| 388 | if (TSTy->isCurrentInstantiation()) { |
| 389 | auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl(); |
| 390 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) |
| 391 | Arguments = CTD->getInjectedTemplateArgs(Context: SemaRef.Context); |
| 392 | else if (auto *Specialization = |
| 393 | dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
| 394 | Arguments = Specialization->getTemplateInstantiationArgs().asArray(); |
| 395 | } |
| 396 | Result.addOuterTemplateArguments( |
| 397 | AssociatedDecl: TSTy->getTemplateName().getAsTemplateDecl(), Args: Arguments, |
| 398 | /*Final=*/false); |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | return Response::ChangeDecl(Ctx: FTD->getLexicalDeclContext()); |
| 403 | } |
| 404 | |
| 405 | Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec, |
| 406 | MultiLevelTemplateArgumentList &Result, |
| 407 | ASTContext &Context, |
| 408 | bool ForConstraintInstantiation) { |
| 409 | if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) { |
| 410 | assert( |
| 411 | (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && |
| 412 | "Outer template not instantiated?" ); |
| 413 | if (ClassTemplate->isMemberSpecialization()) |
| 414 | return Response::Done(); |
| 415 | if (ForConstraintInstantiation) |
| 416 | Result.addOuterTemplateArguments( |
| 417 | AssociatedDecl: const_cast<CXXRecordDecl *>(Rec), |
| 418 | Args: ClassTemplate->getInjectedTemplateArgs(Context: SemaRef.Context), |
| 419 | /*Final=*/false); |
| 420 | } |
| 421 | |
| 422 | if (const MemberSpecializationInfo *MSInfo = |
| 423 | Rec->getMemberSpecializationInfo()) |
| 424 | if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
| 425 | return Response::Done(); |
| 426 | |
| 427 | bool IsFriend = Rec->getFriendObjectKind() || |
| 428 | (Rec->getDescribedClassTemplate() && |
| 429 | Rec->getDescribedClassTemplate()->getFriendObjectKind()); |
| 430 | if (ForConstraintInstantiation && IsFriend && |
| 431 | Rec->getNonTransparentDeclContext()->isFileContext()) { |
| 432 | return Response::ChangeDecl(Ctx: Rec->getLexicalDeclContext()); |
| 433 | } |
| 434 | |
| 435 | // This is to make sure we pick up the VarTemplateSpecializationDecl or the |
| 436 | // TypeAliasTemplateDecl that this lambda is defined inside of. |
| 437 | if (Rec->isLambda()) { |
| 438 | if (const Decl *LCD = Rec->getLambdaContextDecl()) |
| 439 | return Response::ChangeDecl(ND: LCD); |
| 440 | // Retrieve the template arguments for a using alias declaration. |
| 441 | // This is necessary for constraint checking, since we always keep |
| 442 | // constraints relative to the primary template. |
| 443 | if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef); |
| 444 | ForConstraintInstantiation && TypeAlias) { |
| 445 | if (isLambdaEnclosedByTypeAliasDecl(LambdaCallOperator: Rec->getLambdaCallOperator(), |
| 446 | PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) { |
| 447 | Result.addOuterTemplateArguments(AssociatedDecl: TypeAlias.Template, |
| 448 | Args: TypeAlias.AssociatedTemplateArguments, |
| 449 | /*Final=*/false); |
| 450 | // Visit the parent of the current type alias declaration rather than |
| 451 | // the lambda thereof. |
| 452 | // E.g., in the following example: |
| 453 | // struct S { |
| 454 | // template <class> using T = decltype([]<Concept> {} ()); |
| 455 | // }; |
| 456 | // void foo() { |
| 457 | // S::T var; |
| 458 | // } |
| 459 | // The instantiated lambda expression (which we're visiting at 'var') |
| 460 | // has a function DeclContext 'foo' rather than the Record DeclContext |
| 461 | // S. This seems to be an oversight to me that we may want to set a |
| 462 | // Sema Context from the CXXScopeSpec before substituting into T. |
| 463 | return Response::ChangeDecl(Ctx: TypeAlias.Template->getDeclContext()); |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | return Response::UseNextDecl(CurDecl: Rec); |
| 469 | } |
| 470 | |
| 471 | Response HandleImplicitConceptSpecializationDecl( |
| 472 | const ImplicitConceptSpecializationDecl *CSD, |
| 473 | MultiLevelTemplateArgumentList &Result) { |
| 474 | Result.addOuterTemplateArguments( |
| 475 | AssociatedDecl: const_cast<ImplicitConceptSpecializationDecl *>(CSD), |
| 476 | Args: CSD->getTemplateArguments(), |
| 477 | /*Final=*/false); |
| 478 | return Response::UseNextDecl(CurDecl: CSD); |
| 479 | } |
| 480 | |
| 481 | Response HandleGenericDeclContext(const Decl *CurDecl) { |
| 482 | return Response::UseNextDecl(CurDecl); |
| 483 | } |
| 484 | } // namespace TemplateInstArgsHelpers |
| 485 | } // namespace |
| 486 | |
| 487 | MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs( |
| 488 | const NamedDecl *ND, const DeclContext *DC, bool Final, |
| 489 | std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary, |
| 490 | const FunctionDecl *Pattern, bool ForConstraintInstantiation, |
| 491 | bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) { |
| 492 | assert((ND || DC) && "Can't find arguments for a decl if one isn't provided" ); |
| 493 | // Accumulate the set of template argument lists in this structure. |
| 494 | MultiLevelTemplateArgumentList Result; |
| 495 | |
| 496 | using namespace TemplateInstArgsHelpers; |
| 497 | const Decl *CurDecl = ND; |
| 498 | |
| 499 | if (Innermost) { |
| 500 | Result.addOuterTemplateArguments(AssociatedDecl: const_cast<NamedDecl *>(ND), Args: *Innermost, |
| 501 | Final); |
| 502 | // Populate placeholder template arguments for TemplateTemplateParmDecls. |
| 503 | // This is essential for the case e.g. |
| 504 | // |
| 505 | // template <class> concept Concept = false; |
| 506 | // template <template <Concept C> class T> void foo(T<int>) |
| 507 | // |
| 508 | // where parameter C has a depth of 1 but the substituting argument `int` |
| 509 | // has a depth of 0. |
| 510 | if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl)) |
| 511 | HandleDefaultTempArgIntoTempTempParam(TTP, Result); |
| 512 | CurDecl = DC ? Decl::castFromDeclContext(DC) |
| 513 | : Response::UseNextDecl(CurDecl).NextDecl; |
| 514 | } else if (!CurDecl) |
| 515 | CurDecl = Decl::castFromDeclContext(DC); |
| 516 | |
| 517 | while (!CurDecl->isFileContextDecl()) { |
| 518 | Response R; |
| 519 | if (const auto *VarTemplSpec = |
| 520 | dyn_cast<VarTemplateSpecializationDecl>(Val: CurDecl)) { |
| 521 | R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization); |
| 522 | } else if (const auto *PartialClassTemplSpec = |
| 523 | dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: CurDecl)) { |
| 524 | R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result, |
| 525 | SkipForSpecialization); |
| 526 | } else if (const auto *ClassTemplSpec = |
| 527 | dyn_cast<ClassTemplateSpecializationDecl>(Val: CurDecl)) { |
| 528 | R = HandleClassTemplateSpec(ClassTemplSpec, Result, |
| 529 | SkipForSpecialization); |
| 530 | } else if (const auto *Function = dyn_cast<FunctionDecl>(Val: CurDecl)) { |
| 531 | R = HandleFunction(SemaRef&: *this, Function, Result, Pattern, RelativeToPrimary, |
| 532 | ForConstraintInstantiation, |
| 533 | ForDefaultArgumentSubstitution); |
| 534 | } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: CurDecl)) { |
| 535 | R = HandleRecordDecl(SemaRef&: *this, Rec, Result, Context, |
| 536 | ForConstraintInstantiation); |
| 537 | } else if (const auto *CSD = |
| 538 | dyn_cast<ImplicitConceptSpecializationDecl>(Val: CurDecl)) { |
| 539 | R = HandleImplicitConceptSpecializationDecl(CSD, Result); |
| 540 | } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: CurDecl)) { |
| 541 | R = HandleFunctionTemplateDecl(SemaRef&: *this, FTD, Result); |
| 542 | } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(Val: CurDecl)) { |
| 543 | R = Response::ChangeDecl(Ctx: CTD->getLexicalDeclContext()); |
| 544 | } else if (!isa<DeclContext>(Val: CurDecl)) { |
| 545 | R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl); |
| 546 | if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl)) { |
| 547 | R = HandleDefaultTempArgIntoTempTempParam(TTP, Result); |
| 548 | } |
| 549 | } else { |
| 550 | R = HandleGenericDeclContext(CurDecl); |
| 551 | } |
| 552 | |
| 553 | if (R.IsDone) |
| 554 | return Result; |
| 555 | if (R.ClearRelativeToPrimary) |
| 556 | RelativeToPrimary = false; |
| 557 | assert(R.NextDecl); |
| 558 | CurDecl = R.NextDecl; |
| 559 | } |
| 560 | return Result; |
| 561 | } |
| 562 | |
| 563 | bool Sema::CodeSynthesisContext::isInstantiationRecord() const { |
| 564 | switch (Kind) { |
| 565 | case TemplateInstantiation: |
| 566 | case ExceptionSpecInstantiation: |
| 567 | case DefaultTemplateArgumentInstantiation: |
| 568 | case DefaultFunctionArgumentInstantiation: |
| 569 | case ExplicitTemplateArgumentSubstitution: |
| 570 | case DeducedTemplateArgumentSubstitution: |
| 571 | case PriorTemplateArgumentSubstitution: |
| 572 | case ConstraintsCheck: |
| 573 | case NestedRequirementConstraintsCheck: |
| 574 | case ExpansionStmtInstantiation: |
| 575 | return true; |
| 576 | |
| 577 | case RequirementInstantiation: |
| 578 | case RequirementParameterInstantiation: |
| 579 | case DefaultTemplateArgumentChecking: |
| 580 | case DeclaringSpecialMember: |
| 581 | case DeclaringImplicitEqualityComparison: |
| 582 | case DefiningSynthesizedFunction: |
| 583 | case ExceptionSpecEvaluation: |
| 584 | case ConstraintSubstitution: |
| 585 | case ParameterMappingSubstitution: |
| 586 | case RewritingOperatorAsSpaceship: |
| 587 | case InitializingStructuredBinding: |
| 588 | case MarkingClassDllexported: |
| 589 | case BuildingBuiltinDumpStructCall: |
| 590 | case LambdaExpressionSubstitution: |
| 591 | case BuildingDeductionGuides: |
| 592 | case TypeAliasTemplateInstantiation: |
| 593 | case PartialOrderingTTP: |
| 594 | case SYCLKernelLaunchLookup: |
| 595 | case SYCLKernelLaunchOverloadResolution: |
| 596 | return false; |
| 597 | |
| 598 | // This function should never be called when Kind's value is Memoization. |
| 599 | case Memoization: |
| 600 | break; |
| 601 | } |
| 602 | |
| 603 | llvm_unreachable("Invalid SynthesisKind!" ); |
| 604 | } |
| 605 | |
| 606 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 607 | Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, |
| 608 | SourceLocation PointOfInstantiation, SourceRange InstantiationRange, |
| 609 | Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs) |
| 610 | : SemaRef(SemaRef) { |
| 611 | // Don't allow further instantiation if a fatal error and an uncompilable |
| 612 | // error have occurred. Any diagnostics we might have raised will not be |
| 613 | // visible, and we do not need to construct a correct AST. |
| 614 | if (SemaRef.Diags.hasFatalErrorOccurred() && |
| 615 | SemaRef.hasUncompilableErrorOccurred()) { |
| 616 | Invalid = true; |
| 617 | return; |
| 618 | } |
| 619 | |
| 620 | CodeSynthesisContext Inst; |
| 621 | Inst.Kind = Kind; |
| 622 | Inst.PointOfInstantiation = PointOfInstantiation; |
| 623 | Inst.Entity = Entity; |
| 624 | Inst.Template = Template; |
| 625 | Inst.TemplateArgs = TemplateArgs.data(); |
| 626 | Inst.NumTemplateArgs = TemplateArgs.size(); |
| 627 | Inst.InstantiationRange = InstantiationRange; |
| 628 | Inst.InConstraintSubstitution = |
| 629 | Inst.Kind == CodeSynthesisContext::ConstraintSubstitution; |
| 630 | Inst.InParameterMappingSubstitution = |
| 631 | Inst.Kind == CodeSynthesisContext::ParameterMappingSubstitution; |
| 632 | if (!SemaRef.CodeSynthesisContexts.empty()) { |
| 633 | Inst.InConstraintSubstitution |= |
| 634 | SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution; |
| 635 | Inst.InParameterMappingSubstitution |= |
| 636 | SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution; |
| 637 | } |
| 638 | |
| 639 | Invalid = SemaRef.pushCodeSynthesisContext(Ctx: Inst); |
| 640 | } |
| 641 | |
| 642 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 643 | Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, |
| 644 | SourceRange InstantiationRange) |
| 645 | : InstantiatingTemplate(SemaRef, |
| 646 | CodeSynthesisContext::TemplateInstantiation, |
| 647 | PointOfInstantiation, InstantiationRange, Entity) {} |
| 648 | |
| 649 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 650 | Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, |
| 651 | ExceptionSpecification, SourceRange InstantiationRange) |
| 652 | : InstantiatingTemplate( |
| 653 | SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation, |
| 654 | PointOfInstantiation, InstantiationRange, Entity) {} |
| 655 | |
| 656 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 657 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, |
| 658 | TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, |
| 659 | SourceRange InstantiationRange) |
| 660 | : InstantiatingTemplate( |
| 661 | SemaRef, |
| 662 | CodeSynthesisContext::DefaultTemplateArgumentInstantiation, |
| 663 | PointOfInstantiation, InstantiationRange, getAsNamedDecl(P: Param), |
| 664 | Template, TemplateArgs) {} |
| 665 | |
| 666 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 667 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 668 | FunctionTemplateDecl *FunctionTemplate, |
| 669 | ArrayRef<TemplateArgument> TemplateArgs, |
| 670 | CodeSynthesisContext::SynthesisKind Kind, SourceRange InstantiationRange) |
| 671 | : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation, |
| 672 | InstantiationRange, FunctionTemplate, nullptr, |
| 673 | TemplateArgs) { |
| 674 | assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || |
| 675 | Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution || |
| 676 | Kind == CodeSynthesisContext::BuildingDeductionGuides); |
| 677 | } |
| 678 | |
| 679 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 680 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, |
| 681 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 682 | : InstantiatingTemplate( |
| 683 | SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
| 684 | PointOfInstantiation, InstantiationRange, Template, nullptr, |
| 685 | TemplateArgs) {} |
| 686 | |
| 687 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 688 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 689 | ClassTemplatePartialSpecializationDecl *PartialSpec, |
| 690 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 691 | : InstantiatingTemplate( |
| 692 | SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
| 693 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, |
| 694 | TemplateArgs) {} |
| 695 | |
| 696 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 697 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 698 | VarTemplatePartialSpecializationDecl *PartialSpec, |
| 699 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 700 | : InstantiatingTemplate( |
| 701 | SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
| 702 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, |
| 703 | TemplateArgs) {} |
| 704 | |
| 705 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 706 | Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, |
| 707 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 708 | : InstantiatingTemplate( |
| 709 | SemaRef, |
| 710 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation, |
| 711 | PointOfInstantiation, InstantiationRange, Param, nullptr, |
| 712 | TemplateArgs) {} |
| 713 | |
| 714 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 715 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, |
| 716 | NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
| 717 | SourceRange InstantiationRange) |
| 718 | : InstantiatingTemplate( |
| 719 | SemaRef, |
| 720 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, |
| 721 | PointOfInstantiation, InstantiationRange, Param, Template, |
| 722 | TemplateArgs) {} |
| 723 | |
| 724 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 725 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, |
| 726 | TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
| 727 | SourceRange InstantiationRange) |
| 728 | : InstantiatingTemplate( |
| 729 | SemaRef, |
| 730 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, |
| 731 | PointOfInstantiation, InstantiationRange, Param, Template, |
| 732 | TemplateArgs) {} |
| 733 | |
| 734 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 735 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 736 | TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs, |
| 737 | SourceRange InstantiationRange) |
| 738 | : InstantiatingTemplate( |
| 739 | SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation, |
| 740 | PointOfInstantiation, InstantiationRange, /*Entity=*/Entity, |
| 741 | /*Template=*/nullptr, TemplateArgs) {} |
| 742 | |
| 743 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 744 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, |
| 745 | NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
| 746 | SourceRange InstantiationRange) |
| 747 | : InstantiatingTemplate( |
| 748 | SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking, |
| 749 | PointOfInstantiation, InstantiationRange, Param, Template, |
| 750 | TemplateArgs) {} |
| 751 | |
| 752 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 753 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 754 | concepts::Requirement *Req, SourceRange InstantiationRange) |
| 755 | : InstantiatingTemplate( |
| 756 | SemaRef, CodeSynthesisContext::RequirementInstantiation, |
| 757 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 758 | /*Template=*/nullptr, /*TemplateArgs=*/{}) {} |
| 759 | |
| 760 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 761 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 762 | CXXExpansionStmtPattern *ExpansionStmt, ArrayRef<TemplateArgument> TArgs, |
| 763 | SourceRange InstantiationRange) |
| 764 | : InstantiatingTemplate( |
| 765 | SemaRef, CodeSynthesisContext::ExpansionStmtInstantiation, |
| 766 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 767 | /*Template=*/nullptr, /*TemplateArgs=*/TArgs) {} |
| 768 | |
| 769 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 770 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 771 | concepts::NestedRequirement *Req, ConstraintsCheck, |
| 772 | SourceRange InstantiationRange) |
| 773 | : InstantiatingTemplate( |
| 774 | SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck, |
| 775 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 776 | /*Template=*/nullptr, /*TemplateArgs=*/{}) {} |
| 777 | |
| 778 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 779 | Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE, |
| 780 | SourceRange InstantiationRange) |
| 781 | : InstantiatingTemplate( |
| 782 | SemaRef, CodeSynthesisContext::RequirementParameterInstantiation, |
| 783 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 784 | /*Template=*/nullptr, /*TemplateArgs=*/{}) {} |
| 785 | |
| 786 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 787 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 788 | ConstraintsCheck, NamedDecl *Template, |
| 789 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 790 | : InstantiatingTemplate( |
| 791 | SemaRef, CodeSynthesisContext::ConstraintsCheck, |
| 792 | PointOfInstantiation, InstantiationRange, Template, nullptr, |
| 793 | TemplateArgs) {} |
| 794 | |
| 795 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 796 | Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, |
| 797 | NamedDecl *Template, SourceRange InstantiationRange) |
| 798 | : InstantiatingTemplate( |
| 799 | SemaRef, CodeSynthesisContext::ConstraintSubstitution, |
| 800 | PointOfInstantiation, InstantiationRange, Template, nullptr, {}) {} |
| 801 | |
| 802 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 803 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 804 | ParameterMappingSubstitution, NamedDecl *Template, |
| 805 | SourceRange InstantiationRange) |
| 806 | : InstantiatingTemplate( |
| 807 | SemaRef, CodeSynthesisContext::ParameterMappingSubstitution, |
| 808 | PointOfInstantiation, InstantiationRange, Template) {} |
| 809 | |
| 810 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 811 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity, |
| 812 | BuildingDeductionGuidesTag, SourceRange InstantiationRange) |
| 813 | : InstantiatingTemplate( |
| 814 | SemaRef, CodeSynthesisContext::BuildingDeductionGuides, |
| 815 | PointOfInstantiation, InstantiationRange, Entity) {} |
| 816 | |
| 817 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 818 | Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP, |
| 819 | TemplateDecl *PArg, SourceRange InstantiationRange) |
| 820 | : InstantiatingTemplate(SemaRef, CodeSynthesisContext::PartialOrderingTTP, |
| 821 | ArgLoc, InstantiationRange, PArg) {} |
| 822 | |
| 823 | bool Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) { |
| 824 | if (!Ctx.isInstantiationRecord()) { |
| 825 | ++NonInstantiationEntries; |
| 826 | } else { |
| 827 | assert(SemaRef.NonInstantiationEntries <= |
| 828 | SemaRef.CodeSynthesisContexts.size()); |
| 829 | if ((SemaRef.CodeSynthesisContexts.size() - |
| 830 | SemaRef.NonInstantiationEntries) > |
| 831 | SemaRef.getLangOpts().InstantiationDepth) { |
| 832 | SemaRef.Diag(Loc: Ctx.PointOfInstantiation, |
| 833 | DiagID: diag::err_template_recursion_depth_exceeded) |
| 834 | << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange; |
| 835 | SemaRef.Diag(Loc: Ctx.PointOfInstantiation, |
| 836 | DiagID: diag::note_template_recursion_depth) |
| 837 | << SemaRef.getLangOpts().InstantiationDepth; |
| 838 | return true; |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | CodeSynthesisContexts.push_back(Elt: Ctx); |
| 843 | |
| 844 | // Check to see if we're low on stack space. We can't do anything about this |
| 845 | // from here, but we can at least warn the user. |
| 846 | StackHandler.warnOnStackNearlyExhausted(Loc: Ctx.PointOfInstantiation); |
| 847 | return false; |
| 848 | } |
| 849 | |
| 850 | void Sema::popCodeSynthesisContext() { |
| 851 | auto &Active = CodeSynthesisContexts.back(); |
| 852 | if (!Active.isInstantiationRecord()) { |
| 853 | assert(NonInstantiationEntries > 0); |
| 854 | --NonInstantiationEntries; |
| 855 | } |
| 856 | |
| 857 | // Name lookup no longer looks in this template's defining module. |
| 858 | assert(CodeSynthesisContexts.size() >= |
| 859 | CodeSynthesisContextLookupModules.size() && |
| 860 | "forgot to remove a lookup module for a template instantiation" ); |
| 861 | if (CodeSynthesisContexts.size() == |
| 862 | CodeSynthesisContextLookupModules.size()) { |
| 863 | if (Module *M = CodeSynthesisContextLookupModules.back()) |
| 864 | LookupModulesCache.erase(V: M); |
| 865 | CodeSynthesisContextLookupModules.pop_back(); |
| 866 | } |
| 867 | |
| 868 | // If we've left the code synthesis context for the current context stack, |
| 869 | // stop remembering that we've emitted that stack. |
| 870 | if (CodeSynthesisContexts.size() == |
| 871 | LastEmittedCodeSynthesisContextDepth) |
| 872 | LastEmittedCodeSynthesisContextDepth = 0; |
| 873 | |
| 874 | CodeSynthesisContexts.pop_back(); |
| 875 | } |
| 876 | |
| 877 | void Sema::InstantiatingTemplate::Clear() { |
| 878 | if (!Invalid) { |
| 879 | SemaRef.popCodeSynthesisContext(); |
| 880 | Invalid = true; |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | static std::string convertCallArgsToString(Sema &S, |
| 885 | llvm::ArrayRef<const Expr *> Args) { |
| 886 | std::string Result; |
| 887 | llvm::raw_string_ostream OS(Result); |
| 888 | llvm::ListSeparator Comma; |
| 889 | for (const Expr *Arg : Args) { |
| 890 | OS << Comma; |
| 891 | Arg->IgnoreParens()->printPretty(OS, Helper: nullptr, |
| 892 | Policy: S.Context.getPrintingPolicy()); |
| 893 | } |
| 894 | return Result; |
| 895 | } |
| 896 | |
| 897 | static std::string |
| 898 | convertCallArgsValueCategoryAndTypeToString(Sema &S, |
| 899 | llvm::ArrayRef<const Expr *> Args) { |
| 900 | std::string Result; |
| 901 | llvm::raw_string_ostream OS(Result); |
| 902 | llvm::ListSeparator Comma; |
| 903 | OS << "(" ; |
| 904 | for (const Expr *Arg : Args) { |
| 905 | ExprValueKind EVK = Arg->getValueKind(); |
| 906 | const char *ValueCategory = |
| 907 | (EVK == VK_LValue ? "lvalue" |
| 908 | : (EVK == VK_XValue ? "xvalue" : "prvalue" )); |
| 909 | OS << Comma << ValueCategory << " of type '" ; |
| 910 | Arg->getType().print(OS, Policy: S.getPrintingPolicy()); |
| 911 | OS << "'" ; |
| 912 | } |
| 913 | OS << ")" ; |
| 914 | return Result; |
| 915 | } |
| 916 | |
| 917 | void Sema::PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc) { |
| 918 | // Determine which template instantiations to skip, if any. |
| 919 | unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart; |
| 920 | unsigned Limit = Diags.getTemplateBacktraceLimit(); |
| 921 | if (Limit && Limit < CodeSynthesisContexts.size()) { |
| 922 | SkipStart = Limit / 2 + Limit % 2; |
| 923 | SkipEnd = CodeSynthesisContexts.size() - Limit / 2; |
| 924 | } |
| 925 | |
| 926 | // FIXME: In all of these cases, we need to show the template arguments |
| 927 | unsigned InstantiationIdx = 0; |
| 928 | for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator |
| 929 | Active = CodeSynthesisContexts.rbegin(), |
| 930 | ActiveEnd = CodeSynthesisContexts.rend(); |
| 931 | Active != ActiveEnd; |
| 932 | ++Active, ++InstantiationIdx) { |
| 933 | // Skip this instantiation? |
| 934 | if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) { |
| 935 | if (InstantiationIdx == SkipStart) { |
| 936 | // Note that we're skipping instantiations. |
| 937 | DiagFunc(Active->PointOfInstantiation, |
| 938 | PDiag(DiagID: diag::note_instantiation_contexts_suppressed) |
| 939 | << unsigned(CodeSynthesisContexts.size() - Limit)); |
| 940 | } |
| 941 | continue; |
| 942 | } |
| 943 | |
| 944 | switch (Active->Kind) { |
| 945 | case CodeSynthesisContext::TemplateInstantiation: { |
| 946 | Decl *D = Active->Entity; |
| 947 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
| 948 | unsigned DiagID = diag::note_template_member_class_here; |
| 949 | if (isa<ClassTemplateSpecializationDecl>(Val: Record)) |
| 950 | DiagID = diag::note_template_class_instantiation_here; |
| 951 | DiagFunc(Active->PointOfInstantiation, |
| 952 | PDiag(DiagID) << Record << Active->InstantiationRange); |
| 953 | } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D)) { |
| 954 | unsigned DiagID; |
| 955 | if (Function->getPrimaryTemplate()) |
| 956 | DiagID = diag::note_function_template_spec_here; |
| 957 | else |
| 958 | DiagID = diag::note_template_member_function_here; |
| 959 | DiagFunc(Active->PointOfInstantiation, |
| 960 | PDiag(DiagID) << Function << Active->InstantiationRange); |
| 961 | } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
| 962 | DiagFunc(Active->PointOfInstantiation, |
| 963 | PDiag(DiagID: VD->isStaticDataMember() |
| 964 | ? diag::note_template_static_data_member_def_here |
| 965 | : diag::note_template_variable_def_here) |
| 966 | << VD << Active->InstantiationRange); |
| 967 | } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: D)) { |
| 968 | DiagFunc(Active->PointOfInstantiation, |
| 969 | PDiag(DiagID: diag::note_template_enum_def_here) |
| 970 | << ED << Active->InstantiationRange); |
| 971 | } else if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: D)) { |
| 972 | DiagFunc(Active->PointOfInstantiation, |
| 973 | PDiag(DiagID: diag::note_template_nsdmi_here) |
| 974 | << FD << Active->InstantiationRange); |
| 975 | } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) { |
| 976 | DiagFunc(Active->PointOfInstantiation, |
| 977 | PDiag(DiagID: diag::note_template_class_instantiation_here) |
| 978 | << CTD << Active->InstantiationRange); |
| 979 | } |
| 980 | break; |
| 981 | } |
| 982 | |
| 983 | case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: { |
| 984 | TemplateDecl *Template = cast<TemplateDecl>(Val: Active->Template); |
| 985 | SmallString<128> TemplateArgsStr; |
| 986 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
| 987 | Template->printName(OS, Policy: getPrintingPolicy()); |
| 988 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
| 989 | Policy: getPrintingPolicy()); |
| 990 | DiagFunc(Active->PointOfInstantiation, |
| 991 | PDiag(DiagID: diag::note_default_arg_instantiation_here) |
| 992 | << OS.str() << Active->InstantiationRange); |
| 993 | break; |
| 994 | } |
| 995 | |
| 996 | case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: { |
| 997 | FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Val: Active->Entity); |
| 998 | DiagFunc(Active->PointOfInstantiation, |
| 999 | PDiag(DiagID: diag::note_explicit_template_arg_substitution_here) |
| 1000 | << FnTmpl |
| 1001 | << getTemplateArgumentBindingsText( |
| 1002 | Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs, |
| 1003 | NumArgs: Active->NumTemplateArgs) |
| 1004 | << Active->InstantiationRange); |
| 1005 | break; |
| 1006 | } |
| 1007 | |
| 1008 | case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: { |
| 1009 | if (FunctionTemplateDecl *FnTmpl = |
| 1010 | dyn_cast<FunctionTemplateDecl>(Val: Active->Entity)) { |
| 1011 | DiagFunc( |
| 1012 | Active->PointOfInstantiation, |
| 1013 | PDiag(DiagID: diag::note_function_template_deduction_instantiation_here) |
| 1014 | << FnTmpl |
| 1015 | << getTemplateArgumentBindingsText( |
| 1016 | Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs, |
| 1017 | NumArgs: Active->NumTemplateArgs) |
| 1018 | << Active->InstantiationRange); |
| 1019 | } else { |
| 1020 | bool IsVar = isa<VarTemplateDecl>(Val: Active->Entity) || |
| 1021 | isa<VarTemplateSpecializationDecl>(Val: Active->Entity); |
| 1022 | bool IsTemplate = false; |
| 1023 | TemplateParameterList *Params; |
| 1024 | if (auto *D = dyn_cast<TemplateDecl>(Val: Active->Entity)) { |
| 1025 | IsTemplate = true; |
| 1026 | Params = D->getTemplateParameters(); |
| 1027 | } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>( |
| 1028 | Val: Active->Entity)) { |
| 1029 | Params = D->getTemplateParameters(); |
| 1030 | } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>( |
| 1031 | Val: Active->Entity)) { |
| 1032 | Params = D->getTemplateParameters(); |
| 1033 | } else { |
| 1034 | llvm_unreachable("unexpected template kind" ); |
| 1035 | } |
| 1036 | |
| 1037 | DiagFunc(Active->PointOfInstantiation, |
| 1038 | PDiag(DiagID: diag::note_deduced_template_arg_substitution_here) |
| 1039 | << IsVar << IsTemplate << cast<NamedDecl>(Val: Active->Entity) |
| 1040 | << getTemplateArgumentBindingsText(Params, |
| 1041 | Args: Active->TemplateArgs, |
| 1042 | NumArgs: Active->NumTemplateArgs) |
| 1043 | << Active->InstantiationRange); |
| 1044 | } |
| 1045 | break; |
| 1046 | } |
| 1047 | |
| 1048 | case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: { |
| 1049 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: Active->Entity); |
| 1050 | FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext()); |
| 1051 | |
| 1052 | SmallString<128> TemplateArgsStr; |
| 1053 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
| 1054 | FD->printName(OS, Policy: getPrintingPolicy()); |
| 1055 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
| 1056 | Policy: getPrintingPolicy()); |
| 1057 | DiagFunc(Active->PointOfInstantiation, |
| 1058 | PDiag(DiagID: diag::note_default_function_arg_instantiation_here) |
| 1059 | << OS.str() << Active->InstantiationRange); |
| 1060 | break; |
| 1061 | } |
| 1062 | |
| 1063 | case CodeSynthesisContext::PriorTemplateArgumentSubstitution: { |
| 1064 | NamedDecl *Parm = cast<NamedDecl>(Val: Active->Entity); |
| 1065 | std::string Name; |
| 1066 | if (!Parm->getName().empty()) |
| 1067 | Name = std::string(" '" ) + Parm->getName().str() + "'" ; |
| 1068 | |
| 1069 | TemplateParameterList *TemplateParams = nullptr; |
| 1070 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template)) |
| 1071 | TemplateParams = Template->getTemplateParameters(); |
| 1072 | else |
| 1073 | TemplateParams = |
| 1074 | cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template) |
| 1075 | ->getTemplateParameters(); |
| 1076 | DiagFunc(Active->PointOfInstantiation, |
| 1077 | PDiag(DiagID: diag::note_prior_template_arg_substitution) |
| 1078 | << isa<TemplateTemplateParmDecl>(Val: Parm) << Name |
| 1079 | << getTemplateArgumentBindingsText(Params: TemplateParams, |
| 1080 | Args: Active->TemplateArgs, |
| 1081 | NumArgs: Active->NumTemplateArgs) |
| 1082 | << Active->InstantiationRange); |
| 1083 | break; |
| 1084 | } |
| 1085 | |
| 1086 | case CodeSynthesisContext::DefaultTemplateArgumentChecking: { |
| 1087 | TemplateParameterList *TemplateParams = nullptr; |
| 1088 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template)) |
| 1089 | TemplateParams = Template->getTemplateParameters(); |
| 1090 | else |
| 1091 | TemplateParams = |
| 1092 | cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template) |
| 1093 | ->getTemplateParameters(); |
| 1094 | |
| 1095 | DiagFunc(Active->PointOfInstantiation, |
| 1096 | PDiag(DiagID: diag::note_template_default_arg_checking) |
| 1097 | << getTemplateArgumentBindingsText(Params: TemplateParams, |
| 1098 | Args: Active->TemplateArgs, |
| 1099 | NumArgs: Active->NumTemplateArgs) |
| 1100 | << Active->InstantiationRange); |
| 1101 | break; |
| 1102 | } |
| 1103 | |
| 1104 | case CodeSynthesisContext::ExceptionSpecEvaluation: |
| 1105 | DiagFunc(Active->PointOfInstantiation, |
| 1106 | PDiag(DiagID: diag::note_evaluating_exception_spec_here) |
| 1107 | << cast<FunctionDecl>(Val: Active->Entity)); |
| 1108 | break; |
| 1109 | |
| 1110 | case CodeSynthesisContext::ExceptionSpecInstantiation: |
| 1111 | DiagFunc(Active->PointOfInstantiation, |
| 1112 | PDiag(DiagID: diag::note_template_exception_spec_instantiation_here) |
| 1113 | << cast<FunctionDecl>(Val: Active->Entity) |
| 1114 | << Active->InstantiationRange); |
| 1115 | break; |
| 1116 | |
| 1117 | case CodeSynthesisContext::RequirementInstantiation: |
| 1118 | DiagFunc(Active->PointOfInstantiation, |
| 1119 | PDiag(DiagID: diag::note_template_requirement_instantiation_here) |
| 1120 | << Active->InstantiationRange); |
| 1121 | break; |
| 1122 | case CodeSynthesisContext::RequirementParameterInstantiation: |
| 1123 | DiagFunc(Active->PointOfInstantiation, |
| 1124 | PDiag(DiagID: diag::note_template_requirement_params_instantiation_here) |
| 1125 | << Active->InstantiationRange); |
| 1126 | break; |
| 1127 | |
| 1128 | case CodeSynthesisContext::NestedRequirementConstraintsCheck: |
| 1129 | DiagFunc(Active->PointOfInstantiation, |
| 1130 | PDiag(DiagID: diag::note_nested_requirement_here) |
| 1131 | << Active->InstantiationRange); |
| 1132 | break; |
| 1133 | |
| 1134 | case CodeSynthesisContext::DeclaringSpecialMember: |
| 1135 | DiagFunc(Active->PointOfInstantiation, |
| 1136 | PDiag(DiagID: diag::note_in_declaration_of_implicit_special_member) |
| 1137 | << cast<CXXRecordDecl>(Val: Active->Entity) |
| 1138 | << Active->SpecialMember); |
| 1139 | break; |
| 1140 | |
| 1141 | case CodeSynthesisContext::DeclaringImplicitEqualityComparison: |
| 1142 | DiagFunc( |
| 1143 | Active->Entity->getLocation(), |
| 1144 | PDiag(DiagID: diag::note_in_declaration_of_implicit_equality_comparison)); |
| 1145 | break; |
| 1146 | |
| 1147 | case CodeSynthesisContext::DefiningSynthesizedFunction: { |
| 1148 | // FIXME: For synthesized functions that are not defaulted, |
| 1149 | // produce a note. |
| 1150 | auto *FD = dyn_cast<FunctionDecl>(Val: Active->Entity); |
| 1151 | // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind() |
| 1152 | // will ensure that DFK.isComparison() is false. This is important because |
| 1153 | // we will uncondtionally dereference FD in the else if. |
| 1154 | DefaultedFunctionKind DFK = |
| 1155 | FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind(); |
| 1156 | if (DFK.isSpecialMember()) { |
| 1157 | auto *MD = cast<CXXMethodDecl>(Val: FD); |
| 1158 | DiagFunc(Active->PointOfInstantiation, |
| 1159 | PDiag(DiagID: diag::note_member_synthesized_at) |
| 1160 | << MD->isExplicitlyDefaulted() << DFK.asSpecialMember() |
| 1161 | << Context.getCanonicalTagType(TD: MD->getParent())); |
| 1162 | } else if (DFK.isComparison()) { |
| 1163 | QualType RecordType = FD->getParamDecl(i: 0) |
| 1164 | ->getType() |
| 1165 | .getNonReferenceType() |
| 1166 | .getUnqualifiedType(); |
| 1167 | DiagFunc(Active->PointOfInstantiation, |
| 1168 | PDiag(DiagID: diag::note_comparison_synthesized_at) |
| 1169 | << (int)DFK.asComparison() << RecordType); |
| 1170 | } |
| 1171 | break; |
| 1172 | } |
| 1173 | |
| 1174 | case CodeSynthesisContext::RewritingOperatorAsSpaceship: |
| 1175 | DiagFunc(Active->Entity->getLocation(), |
| 1176 | PDiag(DiagID: diag::note_rewriting_operator_as_spaceship)); |
| 1177 | break; |
| 1178 | |
| 1179 | case CodeSynthesisContext::InitializingStructuredBinding: |
| 1180 | DiagFunc(Active->PointOfInstantiation, |
| 1181 | PDiag(DiagID: diag::note_in_binding_decl_init) |
| 1182 | << cast<BindingDecl>(Val: Active->Entity)); |
| 1183 | break; |
| 1184 | |
| 1185 | case CodeSynthesisContext::MarkingClassDllexported: |
| 1186 | DiagFunc(Active->PointOfInstantiation, |
| 1187 | PDiag(DiagID: diag::note_due_to_dllexported_class) |
| 1188 | << cast<CXXRecordDecl>(Val: Active->Entity) |
| 1189 | << !getLangOpts().CPlusPlus11); |
| 1190 | break; |
| 1191 | |
| 1192 | case CodeSynthesisContext::BuildingBuiltinDumpStructCall: |
| 1193 | DiagFunc(Active->PointOfInstantiation, |
| 1194 | PDiag(DiagID: diag::note_building_builtin_dump_struct_call) |
| 1195 | << convertCallArgsToString( |
| 1196 | S&: *this, Args: llvm::ArrayRef(Active->CallArgs, |
| 1197 | Active->NumCallArgs))); |
| 1198 | break; |
| 1199 | |
| 1200 | case CodeSynthesisContext::Memoization: |
| 1201 | break; |
| 1202 | |
| 1203 | case CodeSynthesisContext::LambdaExpressionSubstitution: |
| 1204 | DiagFunc(Active->PointOfInstantiation, |
| 1205 | PDiag(DiagID: diag::note_lambda_substitution_here)); |
| 1206 | break; |
| 1207 | case CodeSynthesisContext::ConstraintsCheck: { |
| 1208 | unsigned DiagID = 0; |
| 1209 | if (!Active->Entity) { |
| 1210 | DiagFunc(Active->PointOfInstantiation, |
| 1211 | PDiag(DiagID: diag::note_nested_requirement_here) |
| 1212 | << Active->InstantiationRange); |
| 1213 | break; |
| 1214 | } |
| 1215 | if (isa<ConceptDecl>(Val: Active->Entity)) |
| 1216 | DiagID = diag::note_concept_specialization_here; |
| 1217 | else if (isa<TemplateDecl>(Val: Active->Entity)) |
| 1218 | DiagID = diag::note_checking_constraints_for_template_id_here; |
| 1219 | else if (isa<VarTemplatePartialSpecializationDecl>(Val: Active->Entity)) |
| 1220 | DiagID = diag::note_checking_constraints_for_var_spec_id_here; |
| 1221 | else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Active->Entity)) |
| 1222 | DiagID = diag::note_checking_constraints_for_class_spec_id_here; |
| 1223 | else { |
| 1224 | assert(isa<FunctionDecl>(Active->Entity)); |
| 1225 | DiagID = diag::note_checking_constraints_for_function_here; |
| 1226 | } |
| 1227 | SmallString<128> TemplateArgsStr; |
| 1228 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
| 1229 | cast<NamedDecl>(Val: Active->Entity)->printName(OS, Policy: getPrintingPolicy()); |
| 1230 | if (!isa<FunctionDecl>(Val: Active->Entity)) { |
| 1231 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
| 1232 | Policy: getPrintingPolicy()); |
| 1233 | } |
| 1234 | DiagFunc(Active->PointOfInstantiation, |
| 1235 | PDiag(DiagID) << OS.str() << Active->InstantiationRange); |
| 1236 | break; |
| 1237 | } |
| 1238 | case CodeSynthesisContext::ConstraintSubstitution: |
| 1239 | DiagFunc(Active->PointOfInstantiation, |
| 1240 | PDiag(DiagID: diag::note_constraint_substitution_here) |
| 1241 | << Active->InstantiationRange); |
| 1242 | break; |
| 1243 | case CodeSynthesisContext::ParameterMappingSubstitution: |
| 1244 | DiagFunc(Active->PointOfInstantiation, |
| 1245 | PDiag(DiagID: diag::note_parameter_mapping_substitution_here) |
| 1246 | << Active->InstantiationRange); |
| 1247 | break; |
| 1248 | case CodeSynthesisContext::BuildingDeductionGuides: |
| 1249 | DiagFunc(Active->PointOfInstantiation, |
| 1250 | PDiag(DiagID: diag::note_building_deduction_guide_here)); |
| 1251 | break; |
| 1252 | case CodeSynthesisContext::TypeAliasTemplateInstantiation: |
| 1253 | // Workaround for a workaround: don't produce a note if we are merely |
| 1254 | // instantiating some other template which contains this alias template. |
| 1255 | // This would be redundant either with the error itself, or some other |
| 1256 | // context note attached to it. |
| 1257 | if (Active->NumTemplateArgs == 0) |
| 1258 | break; |
| 1259 | DiagFunc(Active->PointOfInstantiation, |
| 1260 | PDiag(DiagID: diag::note_template_type_alias_instantiation_here) |
| 1261 | << cast<TypeAliasTemplateDecl>(Val: Active->Entity) |
| 1262 | << Active->InstantiationRange); |
| 1263 | break; |
| 1264 | case CodeSynthesisContext::PartialOrderingTTP: |
| 1265 | DiagFunc(Active->PointOfInstantiation, |
| 1266 | PDiag(DiagID: diag::note_template_arg_template_params_mismatch)); |
| 1267 | if (SourceLocation ParamLoc = Active->Entity->getLocation(); |
| 1268 | ParamLoc.isValid()) |
| 1269 | DiagFunc(ParamLoc, PDiag(DiagID: diag::note_template_prev_declaration) |
| 1270 | << /*isTemplateTemplateParam=*/true |
| 1271 | << Active->InstantiationRange); |
| 1272 | break; |
| 1273 | case CodeSynthesisContext::SYCLKernelLaunchLookup: { |
| 1274 | const auto *SKEPAttr = |
| 1275 | Active->Entity->getAttr<SYCLKernelEntryPointAttr>(); |
| 1276 | assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute" ); |
| 1277 | assert(!SKEPAttr->isInvalidAttr() && |
| 1278 | "sycl_kernel_entry_point attribute is invalid" ); |
| 1279 | DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect)); |
| 1280 | DiagFunc(SKEPAttr->getLocation(), |
| 1281 | PDiag(DiagID: diag::note_sycl_kernel_launch_lookup_here) |
| 1282 | << SKEPAttr->getKernelName()); |
| 1283 | break; |
| 1284 | } |
| 1285 | case CodeSynthesisContext::SYCLKernelLaunchOverloadResolution: { |
| 1286 | const auto *SKEPAttr = |
| 1287 | Active->Entity->getAttr<SYCLKernelEntryPointAttr>(); |
| 1288 | assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute" ); |
| 1289 | assert(!SKEPAttr->isInvalidAttr() && |
| 1290 | "sycl_kernel_entry_point attribute is invalid" ); |
| 1291 | DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect)); |
| 1292 | DiagFunc(SKEPAttr->getLocation(), |
| 1293 | PDiag(DiagID: diag::note_sycl_kernel_launch_overload_resolution_here) |
| 1294 | << SKEPAttr->getKernelName() |
| 1295 | << convertCallArgsValueCategoryAndTypeToString( |
| 1296 | S&: *this, Args: llvm::ArrayRef(Active->CallArgs, |
| 1297 | Active->NumCallArgs))); |
| 1298 | break; |
| 1299 | } |
| 1300 | case CodeSynthesisContext::ExpansionStmtInstantiation: |
| 1301 | Diags.Report(Loc: Active->PointOfInstantiation, |
| 1302 | DiagID: diag::note_expansion_stmt_instantiation_here); |
| 1303 | } |
| 1304 | } |
| 1305 | } |
| 1306 | |
| 1307 | //===----------------------------------------------------------------------===/ |
| 1308 | // Template Instantiation for Types |
| 1309 | //===----------------------------------------------------------------------===/ |
| 1310 | namespace { |
| 1311 | |
| 1312 | class TemplateInstantiator : public TreeTransform<TemplateInstantiator> { |
| 1313 | const MultiLevelTemplateArgumentList &TemplateArgs; |
| 1314 | SourceLocation Loc; |
| 1315 | DeclarationName Entity; |
| 1316 | // Whether to evaluate the C++20 constraints or simply substitute into them. |
| 1317 | bool EvaluateConstraints = true; |
| 1318 | bool EvaluateLambdaConstraint = false; |
| 1319 | // Whether Substitution was Incomplete, that is, we tried to substitute in |
| 1320 | // any user provided template arguments which were null. |
| 1321 | bool IsIncomplete = false; |
| 1322 | // Whether an incomplete substituion should be treated as an error. |
| 1323 | bool BailOutOnIncomplete; |
| 1324 | |
| 1325 | std::optional<llvm::FoldingSetNodeID> TemplateArgsHashValue; |
| 1326 | |
| 1327 | // CWG2770: Function parameters should be instantiated when they are |
| 1328 | // needed by a satisfaction check of an atomic constraint or |
| 1329 | // (recursively) by another function parameter. |
| 1330 | bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm); |
| 1331 | |
| 1332 | public: |
| 1333 | typedef TreeTransform<TemplateInstantiator> inherited; |
| 1334 | |
| 1335 | TemplateInstantiator(Sema &SemaRef, |
| 1336 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 1337 | SourceLocation Loc, DeclarationName Entity, |
| 1338 | bool BailOutOnIncomplete = false) |
| 1339 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), |
| 1340 | Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) { |
| 1341 | assert((!SemaRef.CodeSynthesisContexts.empty() || |
| 1342 | SemaRef.isSFINAEContext()) && |
| 1343 | "Cannot perform an instantiation without some context on the " |
| 1344 | "instantiation stack" ); |
| 1345 | } |
| 1346 | |
| 1347 | void setEvaluateConstraints(bool B) { |
| 1348 | EvaluateConstraints = B; |
| 1349 | } |
| 1350 | bool getEvaluateConstraints() { |
| 1351 | return EvaluateConstraints; |
| 1352 | } |
| 1353 | |
| 1354 | inline static struct ForParameterMappingSubstitution_t { |
| 1355 | } ForParameterMappingSubstitution; |
| 1356 | |
| 1357 | inline static struct ForConstraintSubstitution_t { |
| 1358 | } ForConstraintSubstitution; |
| 1359 | |
| 1360 | TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef, |
| 1361 | SourceLocation Loc, |
| 1362 | const MultiLevelTemplateArgumentList &TemplateArgs) |
| 1363 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), |
| 1364 | EvaluateLambdaConstraint(true), BailOutOnIncomplete(false) { |
| 1365 | if (!SemaRef.CurrentCachedTemplateArgs) |
| 1366 | return; |
| 1367 | auto &V = TemplateArgsHashValue.emplace(); |
| 1368 | for (auto &Level : TemplateArgs) |
| 1369 | for (auto &Arg : Level.Args) |
| 1370 | Arg.Profile(ID&: V, Context: SemaRef.Context); |
| 1371 | } |
| 1372 | |
| 1373 | TemplateInstantiator(ForConstraintSubstitution_t, Sema &SemaRef, |
| 1374 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 1375 | SourceLocation Loc, DeclarationName Entity, |
| 1376 | bool BailOutOnIncomplete = false) |
| 1377 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), |
| 1378 | EvaluateLambdaConstraint(true), BailOutOnIncomplete(false) {} |
| 1379 | |
| 1380 | /// Determine whether the given type \p T has already been |
| 1381 | /// transformed. |
| 1382 | /// |
| 1383 | /// For the purposes of template instantiation, a type has already been |
| 1384 | /// transformed if it is NULL or if it is not dependent. |
| 1385 | bool AlreadyTransformed(QualType T); |
| 1386 | |
| 1387 | /// Returns the location of the entity being instantiated, if known. |
| 1388 | SourceLocation getBaseLocation() { return Loc; } |
| 1389 | |
| 1390 | /// Returns the name of the entity being instantiated, if any. |
| 1391 | DeclarationName getBaseEntity() { return Entity; } |
| 1392 | |
| 1393 | /// Returns whether any substitution so far was incomplete. |
| 1394 | bool getIsIncomplete() const { return IsIncomplete; } |
| 1395 | |
| 1396 | /// Sets the "base" location and entity when that |
| 1397 | /// information is known based on another transformation. |
| 1398 | void setBase(SourceLocation Loc, DeclarationName Entity) { |
| 1399 | this->Loc = Loc; |
| 1400 | this->Entity = Entity; |
| 1401 | } |
| 1402 | |
| 1403 | unsigned TransformTemplateDepth(unsigned Depth) { |
| 1404 | return TemplateArgs.getNewDepth(OldDepth: Depth); |
| 1405 | } |
| 1406 | |
| 1407 | bool TryExpandParameterPacks(SourceLocation EllipsisLoc, |
| 1408 | SourceRange PatternRange, |
| 1409 | ArrayRef<UnexpandedParameterPack> Unexpanded, |
| 1410 | bool FailOnPackProducingTemplates, |
| 1411 | bool &ShouldExpand, bool &RetainExpansion, |
| 1412 | UnsignedOrNone &NumExpansions) { |
| 1413 | if (SemaRef.CurrentInstantiationScope && |
| 1414 | (SemaRef.inConstraintSubstitution() || |
| 1415 | SemaRef.inParameterMappingSubstitution())) { |
| 1416 | for (UnexpandedParameterPack ParmPack : Unexpanded) { |
| 1417 | NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>(); |
| 1418 | if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(Val: VD); |
| 1419 | PVD && maybeInstantiateFunctionParameterToScope(OldParm: PVD)) |
| 1420 | return true; |
| 1421 | } |
| 1422 | } |
| 1423 | |
| 1424 | return getSema().CheckParameterPacksForExpansion( |
| 1425 | EllipsisLoc, PatternRange, Unexpanded, TemplateArgs, |
| 1426 | FailOnPackProducingTemplates, ShouldExpand, RetainExpansion, |
| 1427 | NumExpansions); |
| 1428 | } |
| 1429 | |
| 1430 | void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { |
| 1431 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Pack); |
| 1432 | } |
| 1433 | |
| 1434 | TemplateArgument ForgetPartiallySubstitutedPack() { |
| 1435 | TemplateArgument Result; |
| 1436 | if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope |
| 1437 | ->getPartiallySubstitutedPack()) { |
| 1438 | MultiLevelTemplateArgumentList &TemplateArgs = |
| 1439 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
| 1440 | unsigned Depth, Index; |
| 1441 | std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack); |
| 1442 | if (TemplateArgs.hasTemplateArgument(Depth, Index)) { |
| 1443 | Result = TemplateArgs(Depth, Index); |
| 1444 | TemplateArgs.setArgument(Depth, Index, Arg: TemplateArgument()); |
| 1445 | } else { |
| 1446 | IsIncomplete = true; |
| 1447 | if (BailOutOnIncomplete) |
| 1448 | return TemplateArgument(); |
| 1449 | } |
| 1450 | } |
| 1451 | |
| 1452 | return Result; |
| 1453 | } |
| 1454 | |
| 1455 | void RememberPartiallySubstitutedPack(TemplateArgument Arg) { |
| 1456 | if (Arg.isNull()) |
| 1457 | return; |
| 1458 | |
| 1459 | if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope |
| 1460 | ->getPartiallySubstitutedPack()) { |
| 1461 | MultiLevelTemplateArgumentList &TemplateArgs = |
| 1462 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
| 1463 | unsigned Depth, Index; |
| 1464 | std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack); |
| 1465 | TemplateArgs.setArgument(Depth, Index, Arg); |
| 1466 | } |
| 1467 | } |
| 1468 | |
| 1469 | MultiLevelTemplateArgumentList ForgetSubstitution() { |
| 1470 | MultiLevelTemplateArgumentList New; |
| 1471 | New.addOuterRetainedLevels(Num: this->TemplateArgs.getNumLevels()); |
| 1472 | |
| 1473 | MultiLevelTemplateArgumentList Old = |
| 1474 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
| 1475 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = |
| 1476 | std::move(New); |
| 1477 | return Old; |
| 1478 | } |
| 1479 | |
| 1480 | void RememberSubstitution(MultiLevelTemplateArgumentList Old) { |
| 1481 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = |
| 1482 | std::move(Old); |
| 1483 | } |
| 1484 | |
| 1485 | TemplateArgument |
| 1486 | getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) { |
| 1487 | if (TA.getKind() != TemplateArgument::Pack) |
| 1488 | return TA; |
| 1489 | if (SemaRef.ArgPackSubstIndex) |
| 1490 | return SemaRef.getPackSubstitutedTemplateArgument(Arg: TA); |
| 1491 | assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() && |
| 1492 | "unexpected pack arguments in template rewrite" ); |
| 1493 | TemplateArgument Arg = *TA.pack_begin(); |
| 1494 | if (Arg.isPackExpansion()) |
| 1495 | Arg = Arg.getPackExpansionPattern(); |
| 1496 | return Arg; |
| 1497 | } |
| 1498 | |
| 1499 | /// Transform the given declaration by instantiating a reference to |
| 1500 | /// this declaration. |
| 1501 | Decl *TransformDecl(SourceLocation Loc, Decl *D); |
| 1502 | |
| 1503 | void transformAttrs(Decl *Old, Decl *New) { |
| 1504 | SemaRef.InstantiateAttrs(TemplateArgs, Pattern: Old, Inst: New); |
| 1505 | } |
| 1506 | |
| 1507 | void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) { |
| 1508 | if (Old->isParameterPack() && |
| 1509 | (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) { |
| 1510 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Old); |
| 1511 | for (auto *New : NewDecls) |
| 1512 | SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg( |
| 1513 | D: Old, Inst: cast<VarDecl>(Val: New)); |
| 1514 | return; |
| 1515 | } |
| 1516 | |
| 1517 | assert(NewDecls.size() == 1 && |
| 1518 | "should only have multiple expansions for a pack" ); |
| 1519 | Decl *New = NewDecls.front(); |
| 1520 | |
| 1521 | // If we've instantiated the call operator of a lambda or the call |
| 1522 | // operator template of a generic lambda, update the "instantiation of" |
| 1523 | // information. |
| 1524 | auto *NewMD = dyn_cast<CXXMethodDecl>(Val: New); |
| 1525 | if (NewMD && isLambdaCallOperator(MD: NewMD)) { |
| 1526 | auto *OldMD = dyn_cast<CXXMethodDecl>(Val: Old); |
| 1527 | if (auto *NewTD = NewMD->getDescribedFunctionTemplate()) |
| 1528 | NewTD->setInstantiatedFromMemberTemplate( |
| 1529 | OldMD->getDescribedFunctionTemplate()); |
| 1530 | else |
| 1531 | NewMD->setInstantiationOfMemberFunction(FD: OldMD, |
| 1532 | TSK: TSK_ImplicitInstantiation); |
| 1533 | } |
| 1534 | |
| 1535 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: Old, Inst: New); |
| 1536 | |
| 1537 | // We recreated a local declaration, but not by instantiating it. There |
| 1538 | // may be pending dependent diagnostics to produce. |
| 1539 | if (auto *DC = dyn_cast<DeclContext>(Val: Old); |
| 1540 | DC && DC->isDependentContext() && DC->isFunctionOrMethod()) |
| 1541 | SemaRef.PerformDependentDiagnostics(Pattern: DC, TemplateArgs); |
| 1542 | } |
| 1543 | |
| 1544 | /// Transform the definition of the given declaration by |
| 1545 | /// instantiating it. |
| 1546 | Decl *TransformDefinition(SourceLocation Loc, Decl *D); |
| 1547 | |
| 1548 | /// Transform the first qualifier within a scope by instantiating the |
| 1549 | /// declaration. |
| 1550 | NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); |
| 1551 | |
| 1552 | bool TransformExceptionSpec(SourceLocation Loc, |
| 1553 | FunctionProtoType::ExceptionSpecInfo &ESI, |
| 1554 | SmallVectorImpl<QualType> &Exceptions, |
| 1555 | bool &Changed); |
| 1556 | |
| 1557 | /// Rebuild the exception declaration and register the declaration |
| 1558 | /// as an instantiated local. |
| 1559 | VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, |
| 1560 | TypeSourceInfo *Declarator, |
| 1561 | SourceLocation StartLoc, |
| 1562 | SourceLocation NameLoc, |
| 1563 | IdentifierInfo *Name); |
| 1564 | |
| 1565 | /// Rebuild the Objective-C exception declaration and register the |
| 1566 | /// declaration as an instantiated local. |
| 1567 | VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, |
| 1568 | TypeSourceInfo *TSInfo, QualType T); |
| 1569 | |
| 1570 | TemplateName |
| 1571 | TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc, |
| 1572 | SourceLocation TemplateKWLoc, TemplateName Name, |
| 1573 | SourceLocation NameLoc, |
| 1574 | QualType ObjectType = QualType(), |
| 1575 | NamedDecl *FirstQualifierInScope = nullptr, |
| 1576 | bool AllowInjectedClassName = false); |
| 1577 | |
| 1578 | const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA); |
| 1579 | const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA); |
| 1580 | const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH); |
| 1581 | const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS, |
| 1582 | const Stmt *InstS, |
| 1583 | const NoInlineAttr *A); |
| 1584 | const AlwaysInlineAttr * |
| 1585 | TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS, |
| 1586 | const AlwaysInlineAttr *A); |
| 1587 | const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA); |
| 1588 | const OpenACCRoutineDeclAttr * |
| 1589 | TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A); |
| 1590 | ExprResult TransformPredefinedExpr(PredefinedExpr *E); |
| 1591 | ExprResult TransformDeclRefExpr(DeclRefExpr *E); |
| 1592 | ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); |
| 1593 | |
| 1594 | ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, |
| 1595 | NonTypeTemplateParmDecl *D); |
| 1596 | |
| 1597 | /// Rebuild a DeclRefExpr for a VarDecl reference. |
| 1598 | ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc); |
| 1599 | |
| 1600 | /// Transform a reference to a function or init-capture parameter pack. |
| 1601 | ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD); |
| 1602 | |
| 1603 | /// Transform a FunctionParmPackExpr which was built when we couldn't |
| 1604 | /// expand a function parameter pack reference which refers to an expanded |
| 1605 | /// pack. |
| 1606 | ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E); |
| 1607 | |
| 1608 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, |
| 1609 | FunctionProtoTypeLoc TL) { |
| 1610 | // Call the base version; it will forward to our overridden version below. |
| 1611 | return inherited::TransformFunctionProtoType(TLB, TL); |
| 1612 | } |
| 1613 | |
| 1614 | QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) { |
| 1615 | auto Type = inherited::TransformTagType(TLB, TL); |
| 1616 | if (!Type.isNull()) |
| 1617 | return Type; |
| 1618 | // Special case for transforming a deduction guide, we return a |
| 1619 | // transformed TemplateSpecializationType. |
| 1620 | // FIXME: Why is this hack necessary? |
| 1621 | if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val: TL.getTypePtr()); |
| 1622 | ICNT && SemaRef.CodeSynthesisContexts.back().Kind == |
| 1623 | Sema::CodeSynthesisContext::BuildingDeductionGuides) { |
| 1624 | Type = inherited::TransformType( |
| 1625 | T: ICNT->getDecl()->getCanonicalTemplateSpecializationType( |
| 1626 | Ctx: SemaRef.Context)); |
| 1627 | TLB.pushTrivial(Context&: SemaRef.Context, T: Type, Loc: TL.getNameLoc()); |
| 1628 | } |
| 1629 | return Type; |
| 1630 | } |
| 1631 | |
| 1632 | // Override the default version to handle a rewrite-template-arg-pack case |
| 1633 | // for building a deduction guide, and to cache substitution results in |
| 1634 | // concepts checking. |
| 1635 | bool TransformTemplateArgument(const TemplateArgumentLoc &Input, |
| 1636 | TemplateArgumentLoc &Output, |
| 1637 | bool Uneval = false) { |
| 1638 | const TemplateArgument &Arg = Input.getArgument(); |
| 1639 | if (auto *Cache = SemaRef.CurrentCachedTemplateArgs; |
| 1640 | Cache && TemplateArgsHashValue) { |
| 1641 | llvm::FoldingSetNodeID ID = *TemplateArgsHashValue; |
| 1642 | ID.AddInteger(I: SemaRef.ArgPackSubstIndex.toInternalRepresentation()); |
| 1643 | // FIXME: We may have better performance if we profile Arg without |
| 1644 | // sugars. |
| 1645 | Arg.Profile(ID, Context: SemaRef.Context); |
| 1646 | // FIXME: Ideally, we should only cache and restore the TemplateArgument |
| 1647 | // and rebuild the uncached TypeLoc separately in place. |
| 1648 | // We choose to accept loss of TypeLoc fidelity in cases where TypeLocs |
| 1649 | // are less critical for performance trade-off: currently, this is only |
| 1650 | // applied to concept substitutions and their valid template arguments. |
| 1651 | if (auto Iter = Cache->find(Val: ID); Iter != Cache->end()) { |
| 1652 | Output = Iter->second; |
| 1653 | return false; |
| 1654 | } |
| 1655 | bool Ret = inherited::TransformTemplateArgument(Input, Output, Uneval); |
| 1656 | if (!Ret) |
| 1657 | Cache->insert(KV: {ID, Output}); |
| 1658 | return Ret; |
| 1659 | } |
| 1660 | switch (Arg.getKind()) { |
| 1661 | case TemplateArgument::Pack: { |
| 1662 | std::vector<TemplateArgument> TArgs; |
| 1663 | assert(SemaRef.CodeSynthesisContexts.empty() || |
| 1664 | SemaRef.CodeSynthesisContexts.back().Kind == |
| 1665 | Sema::CodeSynthesisContext::BuildingDeductionGuides); |
| 1666 | // Literally rewrite the template argument pack, instead of unpacking |
| 1667 | // it. |
| 1668 | for (auto &pack : Arg.getPackAsArray()) { |
| 1669 | TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc( |
| 1670 | Arg: pack, NTTPType: QualType(), Loc: SourceLocation{}); |
| 1671 | TemplateArgumentLoc Output; |
| 1672 | if (TransformTemplateArgument(Input, Output, Uneval)) |
| 1673 | return true; // fails |
| 1674 | TArgs.push_back(x: Output.getArgument()); |
| 1675 | } |
| 1676 | Output = SemaRef.getTrivialTemplateArgumentLoc( |
| 1677 | Arg: TemplateArgument(llvm::ArrayRef(TArgs).copy(A&: SemaRef.Context)), |
| 1678 | NTTPType: QualType(), Loc: SourceLocation{}); |
| 1679 | return false; |
| 1680 | } |
| 1681 | default: |
| 1682 | break; |
| 1683 | } |
| 1684 | return inherited::TransformTemplateArgument(Input, Output, Uneval); |
| 1685 | } |
| 1686 | |
| 1687 | using TreeTransform::TransformTemplateSpecializationType; |
| 1688 | QualType |
| 1689 | TransformTemplateSpecializationType(TypeLocBuilder &TLB, |
| 1690 | TemplateSpecializationTypeLoc TL) { |
| 1691 | auto *T = TL.getTypePtr(); |
| 1692 | if (!getSema().ArgPackSubstIndex || !T->isSugared() || |
| 1693 | !isPackProducingBuiltinTemplateName(N: T->getTemplateName())) |
| 1694 | return TreeTransform::TransformTemplateSpecializationType(TLB, TL); |
| 1695 | // Look through sugar to get to the SubstBuiltinTemplatePackType that we |
| 1696 | // need to substitute into. |
| 1697 | |
| 1698 | // `TransformType` code below will handle picking the element from a pack |
| 1699 | // with the index `ArgPackSubstIndex`. |
| 1700 | // FIXME: add ability to represent sugarred type for N-th element of a |
| 1701 | // builtin pack and produce the sugar here. |
| 1702 | QualType R = TransformType(T: T->desugar()); |
| 1703 | TLB.pushTrivial(Context&: getSema().getASTContext(), T: R, Loc: TL.getBeginLoc()); |
| 1704 | return R; |
| 1705 | } |
| 1706 | |
| 1707 | UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution( |
| 1708 | ArrayRef<TemplateArgument> PackArgs) { |
| 1709 | // Don't do this when rewriting template parameters for CTAD: |
| 1710 | // 1) The heuristic needs the unpacked Subst* nodes to figure out the |
| 1711 | // expanded size, but this never applies since Subst* nodes are not |
| 1712 | // created in rewrite scenarios. |
| 1713 | // |
| 1714 | // 2) The heuristic substitutes into the pattern with pack expansion |
| 1715 | // suppressed, which does not meet the requirements for argument |
| 1716 | // rewriting when template arguments include a non-pack matching against |
| 1717 | // a pack, particularly when rewriting an alias CTAD. |
| 1718 | if (TemplateArgs.isRewrite()) |
| 1719 | return std::nullopt; |
| 1720 | |
| 1721 | return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs); |
| 1722 | } |
| 1723 | |
| 1724 | template<typename Fn> |
| 1725 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, |
| 1726 | FunctionProtoTypeLoc TL, |
| 1727 | CXXRecordDecl *ThisContext, |
| 1728 | Qualifiers ThisTypeQuals, |
| 1729 | Fn TransformExceptionSpec); |
| 1730 | |
| 1731 | ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, |
| 1732 | int indexAdjustment, |
| 1733 | UnsignedOrNone NumExpansions, |
| 1734 | bool ExpectParameterPack); |
| 1735 | |
| 1736 | using inherited::TransformTemplateTypeParmType; |
| 1737 | /// Transforms a template type parameter type by performing |
| 1738 | /// substitution of the corresponding template type argument. |
| 1739 | QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
| 1740 | TemplateTypeParmTypeLoc TL, |
| 1741 | bool SuppressObjCLifetime); |
| 1742 | |
| 1743 | QualType BuildSubstTemplateTypeParmType( |
| 1744 | TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, |
| 1745 | Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, |
| 1746 | TemplateArgument Arg, SourceLocation NameLoc); |
| 1747 | |
| 1748 | /// Transforms an already-substituted template type parameter pack |
| 1749 | /// into either itself (if we aren't substituting into its pack expansion) |
| 1750 | /// or the appropriate substituted argument. |
| 1751 | using inherited::TransformSubstTemplateTypeParmPackType; |
| 1752 | QualType |
| 1753 | TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB, |
| 1754 | SubstTemplateTypeParmPackTypeLoc TL, |
| 1755 | bool SuppressObjCLifetime); |
| 1756 | QualType |
| 1757 | TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB, |
| 1758 | SubstBuiltinTemplatePackTypeLoc TL); |
| 1759 | |
| 1760 | CXXRecordDecl::LambdaDependencyKind |
| 1761 | ComputeLambdaDependency(LambdaScopeInfo *LSI) { |
| 1762 | if (auto TypeAlias = |
| 1763 | TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl( |
| 1764 | SemaRef&: getSema()); |
| 1765 | TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl( |
| 1766 | LambdaCallOperator: LSI->CallOperator, PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) { |
| 1767 | unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth(); |
| 1768 | if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels()) |
| 1769 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
| 1770 | for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments) |
| 1771 | if (TA.isDependent()) |
| 1772 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
| 1773 | } |
| 1774 | if (auto *CD = dyn_cast_if_present<ImplicitConceptSpecializationDecl>( |
| 1775 | Val: LSI->Lambda->getLambdaContextDecl())) { |
| 1776 | if (llvm::any_of(Range: CD->getTemplateArguments(), |
| 1777 | P: [](const auto &TA) { return TA.isDependent(); })) |
| 1778 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
| 1779 | } |
| 1780 | return inherited::ComputeLambdaDependency(LSI); |
| 1781 | } |
| 1782 | |
| 1783 | ExprResult TransformLambdaConstraint(Expr *AC) { |
| 1784 | if (AC && EvaluateLambdaConstraint) |
| 1785 | return TransformExpr(E: const_cast<Expr *>(AC)); |
| 1786 | |
| 1787 | return AC; |
| 1788 | } |
| 1789 | |
| 1790 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
| 1791 | // Do not rebuild lambdas to avoid creating a new type. |
| 1792 | // Lambdas have already been processed inside their eval contexts. |
| 1793 | if (SemaRef.RebuildingImmediateInvocation) |
| 1794 | return E; |
| 1795 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true, |
| 1796 | /*InstantiatingLambdaOrBlock=*/true); |
| 1797 | llvm::SaveAndRestore RAII(EvaluateConstraints, EvaluateLambdaConstraint); |
| 1798 | |
| 1799 | return inherited::TransformLambdaExpr(E); |
| 1800 | } |
| 1801 | |
| 1802 | ExprResult TransformBlockExpr(BlockExpr *E) { |
| 1803 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true, |
| 1804 | /*InstantiatingLambdaOrBlock=*/true); |
| 1805 | return inherited::TransformBlockExpr(E); |
| 1806 | } |
| 1807 | |
| 1808 | ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
| 1809 | LambdaScopeInfo *LSI) { |
| 1810 | CXXMethodDecl *MD = LSI->CallOperator; |
| 1811 | for (ParmVarDecl *PVD : MD->parameters()) { |
| 1812 | assert(PVD && "null in a parameter list" ); |
| 1813 | if (!PVD->hasDefaultArg()) |
| 1814 | continue; |
| 1815 | Expr *UninstExpr = PVD->getUninstantiatedDefaultArg(); |
| 1816 | // FIXME: Obtain the source location for the '=' token. |
| 1817 | SourceLocation EqualLoc = UninstExpr->getBeginLoc(); |
| 1818 | if (SemaRef.SubstDefaultArgument(Loc: EqualLoc, Param: PVD, TemplateArgs)) { |
| 1819 | // If substitution fails, the default argument is set to a |
| 1820 | // RecoveryExpr that wraps the uninstantiated default argument so |
| 1821 | // that downstream diagnostics are omitted. |
| 1822 | ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( |
| 1823 | Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), SubExprs: {UninstExpr}, |
| 1824 | T: UninstExpr->getType()); |
| 1825 | if (ErrorResult.isUsable()) |
| 1826 | PVD->setDefaultArg(ErrorResult.get()); |
| 1827 | } |
| 1828 | } |
| 1829 | return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI); |
| 1830 | } |
| 1831 | |
| 1832 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { |
| 1833 | // Currently, we instantiate the body when instantiating the lambda |
| 1834 | // expression. However, `EvaluateConstraints` is disabled during the |
| 1835 | // instantiation of the lambda expression, causing the instantiation |
| 1836 | // failure of the return type requirement in the body. If p0588r1 is fully |
| 1837 | // implemented, the body will be lazily instantiated, and this problem |
| 1838 | // will not occur. Here, `EvaluateConstraints` is temporarily set to |
| 1839 | // `true` to temporarily fix this issue. |
| 1840 | // FIXME: This temporary fix can be removed after fully implementing |
| 1841 | // p0588r1. |
| 1842 | llvm::SaveAndRestore _(EvaluateConstraints, true); |
| 1843 | return inherited::TransformLambdaBody(E, S: Body); |
| 1844 | } |
| 1845 | |
| 1846 | ExprResult TransformRequiresExpr(RequiresExpr *E) { |
| 1847 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); |
| 1848 | ExprResult TransReq = inherited::TransformRequiresExpr(E); |
| 1849 | if (TransReq.isInvalid()) |
| 1850 | return TransReq; |
| 1851 | assert(TransReq.get() != E && |
| 1852 | "Do not change value of isSatisfied for the existing expression. " |
| 1853 | "Create a new expression instead." ); |
| 1854 | if (E->getBody()->isDependentContext()) { |
| 1855 | Sema::SFINAETrap Trap(SemaRef); |
| 1856 | // We recreate the RequiresExpr body, but not by instantiating it. |
| 1857 | // Produce pending diagnostics for dependent access check. |
| 1858 | SemaRef.PerformDependentDiagnostics(Pattern: E->getBody(), TemplateArgs); |
| 1859 | // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis. |
| 1860 | if (Trap.hasErrorOccurred()) |
| 1861 | TransReq.getAs<RequiresExpr>()->setSatisfied(false); |
| 1862 | } |
| 1863 | return TransReq; |
| 1864 | } |
| 1865 | |
| 1866 | bool TransformRequiresExprRequirements( |
| 1867 | ArrayRef<concepts::Requirement *> Reqs, |
| 1868 | SmallVectorImpl<concepts::Requirement *> &Transformed) { |
| 1869 | bool SatisfactionDetermined = false; |
| 1870 | for (concepts::Requirement *Req : Reqs) { |
| 1871 | concepts::Requirement *TransReq = nullptr; |
| 1872 | if (!SatisfactionDetermined) { |
| 1873 | if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Val: Req)) |
| 1874 | TransReq = TransformTypeRequirement(Req: TypeReq); |
| 1875 | else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Val: Req)) |
| 1876 | TransReq = TransformExprRequirement(Req: ExprReq); |
| 1877 | else |
| 1878 | TransReq = TransformNestedRequirement( |
| 1879 | Req: cast<concepts::NestedRequirement>(Val: Req)); |
| 1880 | if (!TransReq) |
| 1881 | return true; |
| 1882 | if (!TransReq->isDependent() && !TransReq->isSatisfied()) |
| 1883 | // [expr.prim.req]p6 |
| 1884 | // [...] The substitution and semantic constraint checking |
| 1885 | // proceeds in lexical order and stops when a condition that |
| 1886 | // determines the result of the requires-expression is |
| 1887 | // encountered. [..] |
| 1888 | SatisfactionDetermined = true; |
| 1889 | } else |
| 1890 | TransReq = Req; |
| 1891 | Transformed.push_back(Elt: TransReq); |
| 1892 | } |
| 1893 | return false; |
| 1894 | } |
| 1895 | |
| 1896 | TemplateParameterList *TransformTemplateParameterList( |
| 1897 | TemplateParameterList *OrigTPL) { |
| 1898 | if (!OrigTPL || !OrigTPL->size()) return OrigTPL; |
| 1899 | |
| 1900 | DeclContext *Owner = OrigTPL->getParam(Idx: 0)->getDeclContext(); |
| 1901 | TemplateDeclInstantiator DeclInstantiator(getSema(), |
| 1902 | /* DeclContext *Owner */ Owner, |
| 1903 | TemplateArgs); |
| 1904 | DeclInstantiator.setEvaluateConstraints(EvaluateConstraints); |
| 1905 | return DeclInstantiator.SubstTemplateParams(List: OrigTPL); |
| 1906 | } |
| 1907 | |
| 1908 | concepts::TypeRequirement * |
| 1909 | TransformTypeRequirement(concepts::TypeRequirement *Req); |
| 1910 | concepts::ExprRequirement * |
| 1911 | TransformExprRequirement(concepts::ExprRequirement *Req); |
| 1912 | concepts::NestedRequirement * |
| 1913 | TransformNestedRequirement(concepts::NestedRequirement *Req); |
| 1914 | ExprResult TransformRequiresTypeParams( |
| 1915 | SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, |
| 1916 | RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, |
| 1917 | SmallVectorImpl<QualType> &PTypes, |
| 1918 | SmallVectorImpl<ParmVarDecl *> &TransParams, |
| 1919 | Sema::ExtParameterInfoBuilder &PInfos); |
| 1920 | |
| 1921 | ExprResult TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) { |
| 1922 | ExprResult Ret = inherited::TransformCXXDynamicCastExpr(E); |
| 1923 | if (Ret.isInvalid()) |
| 1924 | return Ret; |
| 1925 | QualType T = Ret.get()->getType(); |
| 1926 | if (const auto *PT = T->getAsCanonical<PointerType>()) |
| 1927 | T = PT->getPointeeType(); |
| 1928 | auto *DestDecl = T->getAsCXXRecordDecl(); |
| 1929 | if (DestDecl && DestDecl->isEffectivelyFinal()) |
| 1930 | getSema().MarkVTableUsed(Loc: Ret.get()->getExprLoc(), Class: DestDecl); |
| 1931 | return Ret; |
| 1932 | } |
| 1933 | }; |
| 1934 | } |
| 1935 | |
| 1936 | bool TemplateInstantiator::AlreadyTransformed(QualType T) { |
| 1937 | if (T.isNull()) |
| 1938 | return true; |
| 1939 | |
| 1940 | if (T->isInstantiationDependentType() || T->isVariablyModifiedType() || |
| 1941 | T->containsUnexpandedParameterPack()) |
| 1942 | return false; |
| 1943 | |
| 1944 | getSema().MarkDeclarationsReferencedInType(Loc, T); |
| 1945 | return true; |
| 1946 | } |
| 1947 | |
| 1948 | Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { |
| 1949 | if (!D) |
| 1950 | return nullptr; |
| 1951 | |
| 1952 | if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: D)) { |
| 1953 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { |
| 1954 | // If the corresponding template argument is NULL or non-existent, it's |
| 1955 | // because we are performing instantiation from explicitly-specified |
| 1956 | // template arguments in a function template, but there were some |
| 1957 | // arguments left unspecified. |
| 1958 | if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(), |
| 1959 | Index: TTP->getPosition())) { |
| 1960 | IsIncomplete = true; |
| 1961 | return BailOutOnIncomplete ? nullptr : D; |
| 1962 | } |
| 1963 | |
| 1964 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); |
| 1965 | |
| 1966 | if (TTP->isParameterPack()) { |
| 1967 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 1968 | "Missing argument pack" ); |
| 1969 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 1970 | } |
| 1971 | |
| 1972 | TemplateName Template = Arg.getAsTemplate(); |
| 1973 | assert(!Template.isNull() && Template.getAsTemplateDecl() && |
| 1974 | "Wrong kind of template template argument" ); |
| 1975 | return Template.getAsTemplateDecl(); |
| 1976 | } |
| 1977 | |
| 1978 | // Fall through to find the instantiated declaration for this template |
| 1979 | // template parameter. |
| 1980 | } |
| 1981 | |
| 1982 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: D); |
| 1983 | PVD && SemaRef.CurrentInstantiationScope && |
| 1984 | (SemaRef.inConstraintSubstitution() || |
| 1985 | SemaRef.inParameterMappingSubstitution()) && |
| 1986 | maybeInstantiateFunctionParameterToScope(OldParm: PVD)) |
| 1987 | return nullptr; |
| 1988 | |
| 1989 | if (isa<CXXExpansionStmtDecl>(Val: D)) { |
| 1990 | assert(SemaRef.CurrentInstantiationScope); |
| 1991 | return cast<Decl *>( |
| 1992 | Val&: *SemaRef.CurrentInstantiationScope->findInstantiationOf(D)); |
| 1993 | } |
| 1994 | |
| 1995 | return SemaRef.FindInstantiatedDecl(Loc, D: cast<NamedDecl>(Val: D), TemplateArgs); |
| 1996 | } |
| 1997 | |
| 1998 | bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope( |
| 1999 | ParmVarDecl *OldParm) { |
| 2000 | if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(D: OldParm)) |
| 2001 | return false; |
| 2002 | |
| 2003 | if (!OldParm->isParameterPack()) |
| 2004 | return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0, |
| 2005 | /*NumExpansions=*/std::nullopt, |
| 2006 | /*ExpectParameterPack=*/false); |
| 2007 | |
| 2008 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
| 2009 | |
| 2010 | // Find the parameter packs that could be expanded. |
| 2011 | TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc(); |
| 2012 | PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>(); |
| 2013 | TypeLoc Pattern = ExpansionTL.getPatternLoc(); |
| 2014 | SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded); |
| 2015 | assert(!Unexpanded.empty() && "Pack expansion without parameter packs?" ); |
| 2016 | |
| 2017 | bool ShouldExpand = false; |
| 2018 | bool RetainExpansion = false; |
| 2019 | UnsignedOrNone OrigNumExpansions = |
| 2020 | ExpansionTL.getTypePtr()->getNumExpansions(); |
| 2021 | UnsignedOrNone NumExpansions = OrigNumExpansions; |
| 2022 | if (TryExpandParameterPacks(EllipsisLoc: ExpansionTL.getEllipsisLoc(), |
| 2023 | PatternRange: Pattern.getSourceRange(), Unexpanded, |
| 2024 | /*FailOnPackProducingTemplates=*/true, |
| 2025 | ShouldExpand, RetainExpansion, NumExpansions)) |
| 2026 | return true; |
| 2027 | |
| 2028 | assert(ShouldExpand && !RetainExpansion && |
| 2029 | "Shouldn't preserve pack expansion when evaluating constraints" ); |
| 2030 | ExpandingFunctionParameterPack(Pack: OldParm); |
| 2031 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
| 2032 | Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I); |
| 2033 | if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0, |
| 2034 | /*NumExpansions=*/OrigNumExpansions, |
| 2035 | /*ExpectParameterPack=*/false)) |
| 2036 | return true; |
| 2037 | } |
| 2038 | return false; |
| 2039 | } |
| 2040 | |
| 2041 | Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { |
| 2042 | Decl *Inst = getSema().SubstDecl(D, Owner: getSema().CurContext, TemplateArgs); |
| 2043 | if (!Inst) |
| 2044 | return nullptr; |
| 2045 | |
| 2046 | getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
| 2047 | return Inst; |
| 2048 | } |
| 2049 | |
| 2050 | bool TemplateInstantiator::TransformExceptionSpec( |
| 2051 | SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, |
| 2052 | SmallVectorImpl<QualType> &Exceptions, bool &Changed) { |
| 2053 | if (ESI.Type == EST_Uninstantiated) { |
| 2054 | ESI.instantiate(); |
| 2055 | Changed = true; |
| 2056 | } |
| 2057 | return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed); |
| 2058 | } |
| 2059 | |
| 2060 | NamedDecl * |
| 2061 | TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, |
| 2062 | SourceLocation Loc) { |
| 2063 | // If the first part of the nested-name-specifier was a template type |
| 2064 | // parameter, instantiate that type parameter down to a tag type. |
| 2065 | if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(Val: D)) { |
| 2066 | const TemplateTypeParmType *TTP |
| 2067 | = cast<TemplateTypeParmType>(Val: getSema().Context.getTypeDeclType(Decl: TTPD)); |
| 2068 | |
| 2069 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { |
| 2070 | // FIXME: This needs testing w/ member access expressions. |
| 2071 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); |
| 2072 | |
| 2073 | if (TTP->isParameterPack()) { |
| 2074 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 2075 | "Missing argument pack" ); |
| 2076 | |
| 2077 | if (!getSema().ArgPackSubstIndex) |
| 2078 | return nullptr; |
| 2079 | |
| 2080 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2081 | } |
| 2082 | |
| 2083 | QualType T = Arg.getAsType(); |
| 2084 | if (T.isNull()) |
| 2085 | return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D)); |
| 2086 | |
| 2087 | if (const TagType *Tag = T->getAs<TagType>()) |
| 2088 | return Tag->getDecl(); |
| 2089 | |
| 2090 | // The resulting type is not a tag; complain. |
| 2091 | getSema().Diag(Loc, DiagID: diag::err_nested_name_spec_non_tag) << T; |
| 2092 | return nullptr; |
| 2093 | } |
| 2094 | } |
| 2095 | |
| 2096 | return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D)); |
| 2097 | } |
| 2098 | |
| 2099 | VarDecl * |
| 2100 | TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, |
| 2101 | TypeSourceInfo *Declarator, |
| 2102 | SourceLocation StartLoc, |
| 2103 | SourceLocation NameLoc, |
| 2104 | IdentifierInfo *Name) { |
| 2105 | VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator, |
| 2106 | StartLoc, IdLoc: NameLoc, Id: Name); |
| 2107 | if (Var) |
| 2108 | getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var); |
| 2109 | return Var; |
| 2110 | } |
| 2111 | |
| 2112 | VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, |
| 2113 | TypeSourceInfo *TSInfo, |
| 2114 | QualType T) { |
| 2115 | VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TInfo: TSInfo, T); |
| 2116 | if (Var) |
| 2117 | getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var); |
| 2118 | return Var; |
| 2119 | } |
| 2120 | |
| 2121 | TemplateName TemplateInstantiator::TransformTemplateName( |
| 2122 | NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc, |
| 2123 | TemplateName Name, SourceLocation NameLoc, QualType ObjectType, |
| 2124 | NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) { |
| 2125 | if (Name.getKind() == TemplateName::Template) { |
| 2126 | assert(!QualifierLoc && "Unexpected qualifier" ); |
| 2127 | if (auto *TTP = |
| 2128 | dyn_cast<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()); |
| 2129 | TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) { |
| 2130 | // If the corresponding template argument is NULL or non-existent, it's |
| 2131 | // because we are performing instantiation from explicitly-specified |
| 2132 | // template arguments in a function template, but there were some |
| 2133 | // arguments left unspecified. |
| 2134 | if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(), |
| 2135 | Index: TTP->getPosition())) { |
| 2136 | IsIncomplete = true; |
| 2137 | return BailOutOnIncomplete ? TemplateName() : Name; |
| 2138 | } |
| 2139 | |
| 2140 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); |
| 2141 | |
| 2142 | if (TemplateArgs.isRewrite()) { |
| 2143 | // We're rewriting the template parameter as a reference to another |
| 2144 | // template parameter. |
| 2145 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
| 2146 | assert(Arg.getKind() == TemplateArgument::Template && |
| 2147 | "unexpected nontype template argument kind in template rewrite" ); |
| 2148 | return Arg.getAsTemplate(); |
| 2149 | } |
| 2150 | |
| 2151 | auto [AssociatedDecl, Final] = |
| 2152 | TemplateArgs.getAssociatedDecl(Depth: TTP->getDepth()); |
| 2153 | UnsignedOrNone PackIndex = std::nullopt; |
| 2154 | if (TTP->isParameterPack()) { |
| 2155 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 2156 | "Missing argument pack" ); |
| 2157 | |
| 2158 | if (!getSema().ArgPackSubstIndex) { |
| 2159 | // We have the template argument pack to substitute, but we're not |
| 2160 | // actually expanding the enclosing pack expansion yet. So, just |
| 2161 | // keep the entire argument pack. |
| 2162 | return getSema().Context.getSubstTemplateTemplateParmPack( |
| 2163 | ArgPack: Arg, AssociatedDecl, Index: TTP->getIndex(), Final); |
| 2164 | } |
| 2165 | |
| 2166 | PackIndex = SemaRef.getPackIndex(Pack: Arg); |
| 2167 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2168 | } |
| 2169 | |
| 2170 | TemplateName Template = Arg.getAsTemplate(); |
| 2171 | assert(!Template.isNull() && "Null template template argument" ); |
| 2172 | return getSema().Context.getSubstTemplateTemplateParm( |
| 2173 | replacement: Template, AssociatedDecl, Index: TTP->getIndex(), PackIndex, Final); |
| 2174 | } |
| 2175 | } |
| 2176 | |
| 2177 | if (SubstTemplateTemplateParmPackStorage *SubstPack |
| 2178 | = Name.getAsSubstTemplateTemplateParmPack()) { |
| 2179 | if (!getSema().ArgPackSubstIndex) |
| 2180 | return Name; |
| 2181 | |
| 2182 | TemplateArgument Pack = SubstPack->getArgumentPack(); |
| 2183 | TemplateName Template = |
| 2184 | SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack).getAsTemplate(); |
| 2185 | return getSema().Context.getSubstTemplateTemplateParm( |
| 2186 | replacement: Template, AssociatedDecl: SubstPack->getAssociatedDecl(), Index: SubstPack->getIndex(), |
| 2187 | PackIndex: SemaRef.getPackIndex(Pack), Final: SubstPack->getFinal()); |
| 2188 | } |
| 2189 | |
| 2190 | return inherited::TransformTemplateName( |
| 2191 | QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType, |
| 2192 | FirstQualifierInScope, AllowInjectedClassName); |
| 2193 | } |
| 2194 | |
| 2195 | ExprResult |
| 2196 | TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { |
| 2197 | if (!E->isTypeDependent()) |
| 2198 | return E; |
| 2199 | |
| 2200 | return getSema().BuildPredefinedExpr(Loc: E->getLocation(), IK: E->getIdentKind()); |
| 2201 | } |
| 2202 | |
| 2203 | ExprResult |
| 2204 | TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, |
| 2205 | NonTypeTemplateParmDecl *NTTP) { |
| 2206 | if (TemplateArgs.retainInnerDepths() && |
| 2207 | NTTP->getDepth() >= TemplateArgs.getNumLevels()) |
| 2208 | return E; |
| 2209 | // If the corresponding template argument is NULL or non-existent, it's |
| 2210 | // because we are performing instantiation from explicitly-specified |
| 2211 | // template arguments in a function template, but there were some |
| 2212 | // arguments left unspecified. |
| 2213 | if (!TemplateArgs.hasTemplateArgument(Depth: NTTP->getDepth(), |
| 2214 | Index: NTTP->getPosition())) { |
| 2215 | IsIncomplete = true; |
| 2216 | return BailOutOnIncomplete ? ExprError() : E; |
| 2217 | } |
| 2218 | |
| 2219 | TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition()); |
| 2220 | |
| 2221 | if (TemplateArgs.isRewrite()) { |
| 2222 | // We're rewriting the template parameter as a reference to another |
| 2223 | // template parameter. |
| 2224 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
| 2225 | assert(Arg.getKind() == TemplateArgument::Expression && |
| 2226 | "unexpected nontype template argument kind in template rewrite" ); |
| 2227 | // FIXME: This can lead to the same subexpression appearing multiple times |
| 2228 | // in a complete expression. |
| 2229 | return Arg.getAsExpr(); |
| 2230 | } |
| 2231 | |
| 2232 | QualType ParamType = NTTP->isExpandedParameterPack() |
| 2233 | ? NTTP->getExpansionType(I: *SemaRef.ArgPackSubstIndex) |
| 2234 | : NTTP->isParameterPack() && SemaRef.ArgPackSubstIndex |
| 2235 | ? NTTP->getType().getNonPackExpansionType() |
| 2236 | : NTTP->getType(); |
| 2237 | ParamType = SemaRef.SubstType(T: ParamType, TemplateArgs, Loc: E->getLocation(), |
| 2238 | Entity: NTTP->getDeclName()); |
| 2239 | assert(!ParamType.isNull() && "Shouldn't substitute to an invalid type" ); |
| 2240 | |
| 2241 | auto [AssociatedDecl, Final] = |
| 2242 | TemplateArgs.getAssociatedDecl(Depth: NTTP->getDepth()); |
| 2243 | UnsignedOrNone PackIndex = std::nullopt; |
| 2244 | if (NTTP->isParameterPack() || |
| 2245 | // In concept parameter mapping for fold expressions, packs that aren't |
| 2246 | // expanded in place are treated as having non-pack dependency, so that |
| 2247 | // a PackExpansionType won't prevent expanding the packs outside the |
| 2248 | // TreeTransform. However, we still need to unpack the arguments during |
| 2249 | // any template argument substitution, so we also check its FoundDecl. |
| 2250 | (E->getFoundDecl() && E->getFoundDecl() != E->getDecl() && |
| 2251 | E->getFoundDecl()->isParameterPack())) { |
| 2252 | assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack" ); |
| 2253 | |
| 2254 | if (!getSema().ArgPackSubstIndex) { |
| 2255 | // We have an argument pack, but we can't select a particular argument |
| 2256 | // out of it yet. Therefore, we'll build an expression to hold on to that |
| 2257 | // argument pack. |
| 2258 | QualType ExprType = ParamType.getNonLValueExprType(Context: SemaRef.Context); |
| 2259 | if (ParamType->isRecordType()) |
| 2260 | ExprType.addConst(); |
| 2261 | return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr( |
| 2262 | ExprType, ParamType->isReferenceType() ? VK_LValue : VK_PRValue, |
| 2263 | E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final); |
| 2264 | } |
| 2265 | PackIndex = SemaRef.getPackIndex(Pack: Arg); |
| 2266 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2267 | } |
| 2268 | return SemaRef.BuildSubstNonTypeTemplateParmExpr( |
| 2269 | AssociatedDecl, Index: NTTP->getPosition(), ParamType, loc: E->getLocation(), Replacement: Arg, |
| 2270 | PackIndex, Final); |
| 2271 | } |
| 2272 | |
| 2273 | const AnnotateAttr * |
| 2274 | TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) { |
| 2275 | SmallVector<Expr *> Args; |
| 2276 | for (Expr *Arg : AA->args()) { |
| 2277 | ExprResult Res = getDerived().TransformExpr(E: Arg); |
| 2278 | if (Res.isUsable()) |
| 2279 | Args.push_back(Elt: Res.get()); |
| 2280 | } |
| 2281 | return AnnotateAttr::CreateImplicit(Ctx&: getSema().Context, Annotation: AA->getAnnotation(), |
| 2282 | Args: Args.data(), ArgsSize: Args.size(), Range: AA->getRange()); |
| 2283 | } |
| 2284 | |
| 2285 | const CXXAssumeAttr * |
| 2286 | TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) { |
| 2287 | ExprResult Res = getDerived().TransformExpr(E: AA->getAssumption()); |
| 2288 | if (!Res.isUsable()) |
| 2289 | return AA; |
| 2290 | |
| 2291 | if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) { |
| 2292 | Res = getSema().BuildCXXAssumeExpr(Assumption: Res.get(), AttrName: AA->getAttrName(), |
| 2293 | Range: AA->getRange()); |
| 2294 | if (!Res.isUsable()) |
| 2295 | return AA; |
| 2296 | } |
| 2297 | |
| 2298 | return CXXAssumeAttr::CreateImplicit(Ctx&: getSema().Context, Assumption: Res.get(), |
| 2299 | Range: AA->getRange()); |
| 2300 | } |
| 2301 | |
| 2302 | const LoopHintAttr * |
| 2303 | TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) { |
| 2304 | ExprResult TransformedExprResult = getDerived().TransformExpr(E: LH->getValue()); |
| 2305 | if (!TransformedExprResult.isUsable() || |
| 2306 | TransformedExprResult.get() == LH->getValue()) |
| 2307 | return LH; |
| 2308 | Expr *TransformedExpr = TransformedExprResult.get(); |
| 2309 | |
| 2310 | // Generate error if there is a problem with the value. |
| 2311 | if (getSema().CheckLoopHintExpr(E: TransformedExpr, Loc: LH->getLocation(), |
| 2312 | /*AllowZero=*/LH->getSemanticSpelling() == |
| 2313 | LoopHintAttr::Pragma_unroll)) |
| 2314 | return LH; |
| 2315 | |
| 2316 | LoopHintAttr::OptionType Option = LH->getOption(); |
| 2317 | LoopHintAttr::LoopHintState State = LH->getState(); |
| 2318 | |
| 2319 | // Since C++ does not have partial instantiation, we would expect a |
| 2320 | // transformed loop hint expression to not be value dependent. However, at |
| 2321 | // the time of writing, the use of a generic lambda inside a template |
| 2322 | // triggers a double instantiation, so we must protect against this event. |
| 2323 | // This provision may become unneeded in the future. |
| 2324 | if (Option == LoopHintAttr::UnrollCount && |
| 2325 | !TransformedExpr->isValueDependent()) { |
| 2326 | llvm::APSInt ValueAPS = |
| 2327 | TransformedExpr->EvaluateKnownConstInt(Ctx: getSema().getASTContext()); |
| 2328 | // The values of 0 and 1 block any unrolling of the loop (also see |
| 2329 | // handleLoopHintAttr in SemaStmtAttr). |
| 2330 | if (ValueAPS.isZero() || ValueAPS.isOne()) { |
| 2331 | Option = LoopHintAttr::Unroll; |
| 2332 | State = LoopHintAttr::Disable; |
| 2333 | } |
| 2334 | } |
| 2335 | |
| 2336 | // Create new LoopHintValueAttr with integral expression in place of the |
| 2337 | // non-type template parameter. |
| 2338 | return LoopHintAttr::CreateImplicit(Ctx&: getSema().Context, Option, State, |
| 2339 | Value: TransformedExpr, CommonInfo: *LH); |
| 2340 | } |
| 2341 | const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr( |
| 2342 | const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) { |
| 2343 | if (!A || getSema().CheckNoInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A)) |
| 2344 | return nullptr; |
| 2345 | |
| 2346 | return A; |
| 2347 | } |
| 2348 | const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr( |
| 2349 | const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) { |
| 2350 | if (!A || getSema().CheckAlwaysInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A)) |
| 2351 | return nullptr; |
| 2352 | |
| 2353 | return A; |
| 2354 | } |
| 2355 | |
| 2356 | const CodeAlignAttr * |
| 2357 | TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) { |
| 2358 | Expr *TransformedExpr = getDerived().TransformExpr(E: CA->getAlignment()).get(); |
| 2359 | return getSema().BuildCodeAlignAttr(CI: *CA, E: TransformedExpr); |
| 2360 | } |
| 2361 | const OpenACCRoutineDeclAttr * |
| 2362 | TemplateInstantiator::TransformOpenACCRoutineDeclAttr( |
| 2363 | const OpenACCRoutineDeclAttr *A) { |
| 2364 | llvm_unreachable("RoutineDecl should only be a declaration attribute, as it " |
| 2365 | "applies to a Function Decl (and a few places for VarDecl)" ); |
| 2366 | } |
| 2367 | |
| 2368 | ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD, |
| 2369 | SourceLocation Loc) { |
| 2370 | DeclarationNameInfo NameInfo(PD->getDeclName(), Loc); |
| 2371 | return getSema().BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo, D: PD); |
| 2372 | } |
| 2373 | |
| 2374 | ExprResult |
| 2375 | TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) { |
| 2376 | if (getSema().ArgPackSubstIndex) { |
| 2377 | // We can expand this parameter pack now. |
| 2378 | ValueDecl *D = E->getExpansion(I: *getSema().ArgPackSubstIndex); |
| 2379 | ValueDecl *VD = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D)); |
| 2380 | if (!VD) |
| 2381 | return ExprError(); |
| 2382 | return RebuildVarDeclRefExpr(PD: VD, Loc: E->getExprLoc()); |
| 2383 | } |
| 2384 | |
| 2385 | QualType T = TransformType(T: E->getType()); |
| 2386 | if (T.isNull()) |
| 2387 | return ExprError(); |
| 2388 | |
| 2389 | // Transform each of the parameter expansions into the corresponding |
| 2390 | // parameters in the instantiation of the function decl. |
| 2391 | SmallVector<ValueDecl *, 8> Vars; |
| 2392 | Vars.reserve(N: E->getNumExpansions()); |
| 2393 | for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end(); |
| 2394 | I != End; ++I) { |
| 2395 | ValueDecl *D = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D: *I)); |
| 2396 | if (!D) |
| 2397 | return ExprError(); |
| 2398 | Vars.push_back(Elt: D); |
| 2399 | } |
| 2400 | |
| 2401 | auto *PackExpr = |
| 2402 | FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: E->getParameterPack(), |
| 2403 | NameLoc: E->getParameterPackLocation(), Params: Vars); |
| 2404 | getSema().MarkFunctionParmPackReferenced(E: PackExpr); |
| 2405 | return PackExpr; |
| 2406 | } |
| 2407 | |
| 2408 | ExprResult |
| 2409 | TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E, |
| 2410 | ValueDecl *PD) { |
| 2411 | typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; |
| 2412 | llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found = |
| 2413 | getSema().CurrentInstantiationScope->getInstantiationOfIfExists(D: PD); |
| 2414 | |
| 2415 | // This can happen when instantiating an expansion statement that contains |
| 2416 | // a pack (e.g. `template for (auto x : {{ts...}})`). |
| 2417 | if (!Found) |
| 2418 | return E; |
| 2419 | |
| 2420 | Decl *TransformedDecl; |
| 2421 | if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: *Found)) { |
| 2422 | // If this is a reference to a function parameter pack which we can |
| 2423 | // substitute but can't yet expand, build a FunctionParmPackExpr for it. |
| 2424 | if (!getSema().ArgPackSubstIndex) { |
| 2425 | QualType T = TransformType(T: E->getType()); |
| 2426 | if (T.isNull()) |
| 2427 | return ExprError(); |
| 2428 | auto *PackExpr = FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: PD, |
| 2429 | NameLoc: E->getExprLoc(), Params: *Pack); |
| 2430 | getSema().MarkFunctionParmPackReferenced(E: PackExpr); |
| 2431 | return PackExpr; |
| 2432 | } |
| 2433 | |
| 2434 | TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex]; |
| 2435 | } else { |
| 2436 | TransformedDecl = cast<Decl *>(Val&: *Found); |
| 2437 | } |
| 2438 | |
| 2439 | // We have either an unexpanded pack or a specific expansion. |
| 2440 | return RebuildVarDeclRefExpr(PD: cast<ValueDecl>(Val: TransformedDecl), |
| 2441 | Loc: E->getExprLoc()); |
| 2442 | } |
| 2443 | |
| 2444 | ExprResult |
| 2445 | TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { |
| 2446 | NamedDecl *D = E->getDecl(); |
| 2447 | |
| 2448 | // Handle references to non-type template parameters and non-type template |
| 2449 | // parameter packs. |
| 2450 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) { |
| 2451 | if (NTTP->getDepth() < TemplateArgs.getNumLevels()) |
| 2452 | return TransformTemplateParmRefExpr(E, NTTP); |
| 2453 | |
| 2454 | // We have a non-type template parameter that isn't fully substituted; |
| 2455 | // FindInstantiatedDecl will find it in the local instantiation scope. |
| 2456 | } |
| 2457 | |
| 2458 | // Handle references to function parameter packs. |
| 2459 | if (VarDecl *PD = dyn_cast<VarDecl>(Val: D)) |
| 2460 | if (PD->isParameterPack()) { |
| 2461 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: PD); |
| 2462 | PVD && SemaRef.CurrentInstantiationScope && |
| 2463 | (SemaRef.inConstraintSubstitution() || |
| 2464 | SemaRef.inParameterMappingSubstitution()) && |
| 2465 | maybeInstantiateFunctionParameterToScope(OldParm: PVD)) |
| 2466 | return ExprError(); |
| 2467 | |
| 2468 | return TransformFunctionParmPackRefExpr(E, PD); |
| 2469 | } |
| 2470 | |
| 2471 | return inherited::TransformDeclRefExpr(E); |
| 2472 | } |
| 2473 | |
| 2474 | ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( |
| 2475 | CXXDefaultArgExpr *E) { |
| 2476 | assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())-> |
| 2477 | getDescribedFunctionTemplate() && |
| 2478 | "Default arg expressions are never formed in dependent cases." ); |
| 2479 | return SemaRef.BuildCXXDefaultArgExpr( |
| 2480 | CallLoc: E->getUsedLocation(), FD: cast<FunctionDecl>(Val: E->getParam()->getDeclContext()), |
| 2481 | Param: E->getParam()); |
| 2482 | } |
| 2483 | |
| 2484 | template<typename Fn> |
| 2485 | QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, |
| 2486 | FunctionProtoTypeLoc TL, |
| 2487 | CXXRecordDecl *ThisContext, |
| 2488 | Qualifiers ThisTypeQuals, |
| 2489 | Fn TransformExceptionSpec) { |
| 2490 | // If this is a lambda or block, the transformation MUST be done in the |
| 2491 | // CurrentInstantiationScope since it introduces a mapping of |
| 2492 | // the original to the newly created transformed parameters. |
| 2493 | // |
| 2494 | // In that case, TemplateInstantiator::TransformLambdaExpr will |
| 2495 | // have already pushed a scope for this prototype, so don't create |
| 2496 | // a second one. |
| 2497 | LocalInstantiationScope *Current = getSema().CurrentInstantiationScope; |
| 2498 | std::optional<LocalInstantiationScope> Scope; |
| 2499 | if (!Current || !Current->isLambdaOrBlock()) |
| 2500 | Scope.emplace(args&: SemaRef, /*CombineWithOuterScope=*/args: true); |
| 2501 | |
| 2502 | return inherited::TransformFunctionProtoType( |
| 2503 | TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec); |
| 2504 | } |
| 2505 | |
| 2506 | ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam( |
| 2507 | ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions, |
| 2508 | bool ExpectParameterPack) { |
| 2509 | auto NewParm = SemaRef.SubstParmVarDecl( |
| 2510 | D: OldParm, TemplateArgs, indexAdjustment, NumExpansions, |
| 2511 | ExpectParameterPack, EvaluateConstraints); |
| 2512 | if (NewParm && SemaRef.getLangOpts().OpenCL) |
| 2513 | SemaRef.deduceOpenCLAddressSpace(decl: NewParm); |
| 2514 | return NewParm; |
| 2515 | } |
| 2516 | |
| 2517 | QualType TemplateInstantiator::BuildSubstTemplateTypeParmType( |
| 2518 | TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, |
| 2519 | Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, |
| 2520 | TemplateArgument Arg, SourceLocation NameLoc) { |
| 2521 | QualType Replacement = Arg.getAsType(); |
| 2522 | |
| 2523 | // If the template parameter had ObjC lifetime qualifiers, |
| 2524 | // then any such qualifiers on the replacement type are ignored. |
| 2525 | if (SuppressObjCLifetime) { |
| 2526 | Qualifiers RQs; |
| 2527 | RQs = Replacement.getQualifiers(); |
| 2528 | RQs.removeObjCLifetime(); |
| 2529 | Replacement = |
| 2530 | SemaRef.Context.getQualifiedType(T: Replacement.getUnqualifiedType(), Qs: RQs); |
| 2531 | } |
| 2532 | |
| 2533 | // TODO: only do this uniquing once, at the start of instantiation. |
| 2534 | QualType Result = getSema().Context.getSubstTemplateTypeParmType( |
| 2535 | Replacement, AssociatedDecl, Index, PackIndex, Final); |
| 2536 | SubstTemplateTypeParmTypeLoc NewTL = |
| 2537 | TLB.push<SubstTemplateTypeParmTypeLoc>(T: Result); |
| 2538 | NewTL.setNameLoc(NameLoc); |
| 2539 | return Result; |
| 2540 | } |
| 2541 | |
| 2542 | QualType |
| 2543 | TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
| 2544 | TemplateTypeParmTypeLoc TL, |
| 2545 | bool SuppressObjCLifetime) { |
| 2546 | const TemplateTypeParmType *T = TL.getTypePtr(); |
| 2547 | if (T->getDepth() < TemplateArgs.getNumLevels()) { |
| 2548 | // Replace the template type parameter with its corresponding |
| 2549 | // template argument. |
| 2550 | |
| 2551 | // If the corresponding template argument is NULL or doesn't exist, it's |
| 2552 | // because we are performing instantiation from explicitly-specified |
| 2553 | // template arguments in a function template class, but there were some |
| 2554 | // arguments left unspecified. |
| 2555 | if (!TemplateArgs.hasTemplateArgument(Depth: T->getDepth(), Index: T->getIndex())) { |
| 2556 | IsIncomplete = true; |
| 2557 | if (BailOutOnIncomplete) |
| 2558 | return QualType(); |
| 2559 | |
| 2560 | TemplateTypeParmTypeLoc NewTL |
| 2561 | = TLB.push<TemplateTypeParmTypeLoc>(T: TL.getType()); |
| 2562 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2563 | return TL.getType(); |
| 2564 | } |
| 2565 | |
| 2566 | TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); |
| 2567 | |
| 2568 | if (TemplateArgs.isRewrite()) { |
| 2569 | // We're rewriting the template parameter as a reference to another |
| 2570 | // template parameter. |
| 2571 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
| 2572 | assert(Arg.getKind() == TemplateArgument::Type && |
| 2573 | "unexpected nontype template argument kind in template rewrite" ); |
| 2574 | QualType NewT = Arg.getAsType(); |
| 2575 | TLB.pushTrivial(Context&: SemaRef.Context, T: NewT, Loc: TL.getNameLoc()); |
| 2576 | return NewT; |
| 2577 | } |
| 2578 | |
| 2579 | auto [AssociatedDecl, Final] = |
| 2580 | TemplateArgs.getAssociatedDecl(Depth: T->getDepth()); |
| 2581 | UnsignedOrNone PackIndex = std::nullopt; |
| 2582 | if (T->isParameterPack() || |
| 2583 | // In concept parameter mapping for fold expressions, packs that aren't |
| 2584 | // expanded in place are treated as having non-pack dependency, so that |
| 2585 | // a PackExpansionType won't prevent expanding the packs outside the |
| 2586 | // TreeTransform. However, we still need to unpack the arguments during |
| 2587 | // any template argument substitution, so we check the associated |
| 2588 | // declaration instead. |
| 2589 | (T->getDecl() && T->getDecl()->isTemplateParameterPack())) { |
| 2590 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 2591 | "Missing argument pack" ); |
| 2592 | |
| 2593 | if (!getSema().ArgPackSubstIndex) { |
| 2594 | // We have the template argument pack, but we're not expanding the |
| 2595 | // enclosing pack expansion yet. Just save the template argument |
| 2596 | // pack for later substitution. |
| 2597 | QualType Result = getSema().Context.getSubstTemplateTypeParmPackType( |
| 2598 | AssociatedDecl, Index: T->getIndex(), Final, ArgPack: Arg); |
| 2599 | SubstTemplateTypeParmPackTypeLoc NewTL |
| 2600 | = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result); |
| 2601 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2602 | return Result; |
| 2603 | } |
| 2604 | |
| 2605 | // PackIndex starts from last element. |
| 2606 | PackIndex = SemaRef.getPackIndex(Pack: Arg); |
| 2607 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2608 | } |
| 2609 | |
| 2610 | assert(Arg.getKind() == TemplateArgument::Type && |
| 2611 | "Template argument kind mismatch" ); |
| 2612 | |
| 2613 | return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final, |
| 2614 | AssociatedDecl, Index: T->getIndex(), |
| 2615 | PackIndex, Arg, NameLoc: TL.getNameLoc()); |
| 2616 | } |
| 2617 | |
| 2618 | // The template type parameter comes from an inner template (e.g., |
| 2619 | // the template parameter list of a member template inside the |
| 2620 | // template we are instantiating). Create a new template type |
| 2621 | // parameter with the template "level" reduced by one. |
| 2622 | TemplateTypeParmDecl *NewTTPDecl = nullptr; |
| 2623 | if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) |
| 2624 | NewTTPDecl = cast_or_null<TemplateTypeParmDecl>( |
| 2625 | Val: TransformDecl(Loc: TL.getNameLoc(), D: OldTTPDecl)); |
| 2626 | QualType Result = getSema().Context.getTemplateTypeParmType( |
| 2627 | Depth: T->getDepth() - (TemplateArgs.retainInnerDepths() |
| 2628 | ? 0 |
| 2629 | : TemplateArgs.getNumSubstitutedLevels()), |
| 2630 | Index: T->getIndex(), ParameterPack: T->isParameterPack(), ParmDecl: NewTTPDecl); |
| 2631 | TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result); |
| 2632 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2633 | return Result; |
| 2634 | } |
| 2635 | |
| 2636 | QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType( |
| 2637 | TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, |
| 2638 | bool SuppressObjCLifetime) { |
| 2639 | const SubstTemplateTypeParmPackType *T = TL.getTypePtr(); |
| 2640 | |
| 2641 | Decl *NewReplaced = TransformDecl(Loc: TL.getNameLoc(), D: T->getAssociatedDecl()); |
| 2642 | |
| 2643 | if (!getSema().ArgPackSubstIndex) { |
| 2644 | // We aren't expanding the parameter pack, so just return ourselves. |
| 2645 | QualType Result = TL.getType(); |
| 2646 | if (NewReplaced != T->getAssociatedDecl()) |
| 2647 | Result = getSema().Context.getSubstTemplateTypeParmPackType( |
| 2648 | AssociatedDecl: NewReplaced, Index: T->getIndex(), Final: T->getFinal(), ArgPack: T->getArgumentPack()); |
| 2649 | SubstTemplateTypeParmPackTypeLoc NewTL = |
| 2650 | TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result); |
| 2651 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2652 | return Result; |
| 2653 | } |
| 2654 | |
| 2655 | TemplateArgument Pack = T->getArgumentPack(); |
| 2656 | TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack); |
| 2657 | return BuildSubstTemplateTypeParmType( |
| 2658 | TLB, SuppressObjCLifetime, Final: T->getFinal(), AssociatedDecl: NewReplaced, Index: T->getIndex(), |
| 2659 | PackIndex: SemaRef.getPackIndex(Pack), Arg, NameLoc: TL.getNameLoc()); |
| 2660 | } |
| 2661 | |
| 2662 | QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType( |
| 2663 | TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) { |
| 2664 | if (!getSema().ArgPackSubstIndex) |
| 2665 | return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL); |
| 2666 | TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument( |
| 2667 | Arg: TL.getTypePtr()->getArgumentPack()); |
| 2668 | TLB.pushTrivial(Context&: SemaRef.getASTContext(), T: Result.getAsType(), |
| 2669 | Loc: TL.getBeginLoc()); |
| 2670 | return Result.getAsType(); |
| 2671 | } |
| 2672 | |
| 2673 | static concepts::Requirement::SubstitutionDiagnostic * |
| 2674 | createSubstDiag(Sema &S, TemplateDeductionInfo &Info, |
| 2675 | Sema::EntityPrinter Printer) { |
| 2676 | SmallString<128> Message; |
| 2677 | SourceLocation ErrorLoc; |
| 2678 | if (Info.hasSFINAEDiagnostic()) { |
| 2679 | PartialDiagnosticAt PDA(SourceLocation(), |
| 2680 | PartialDiagnostic::NullDiagnostic{}); |
| 2681 | Info.takeSFINAEDiagnostic(PD&: PDA); |
| 2682 | PDA.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: Message); |
| 2683 | ErrorLoc = PDA.first; |
| 2684 | } else { |
| 2685 | ErrorLoc = Info.getLocation(); |
| 2686 | } |
| 2687 | SmallString<128> Entity; |
| 2688 | llvm::raw_svector_ostream OS(Entity); |
| 2689 | Printer(OS); |
| 2690 | const ASTContext &C = S.Context; |
| 2691 | return new (C) concepts::Requirement::SubstitutionDiagnostic{ |
| 2692 | .SubstitutedEntity: C.backupStr(S: Entity), .DiagLoc: ErrorLoc, .DiagMessage: C.backupStr(S: Message)}; |
| 2693 | } |
| 2694 | |
| 2695 | concepts::Requirement::SubstitutionDiagnostic * |
| 2696 | Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) { |
| 2697 | SmallString<128> Entity; |
| 2698 | llvm::raw_svector_ostream OS(Entity); |
| 2699 | Printer(OS); |
| 2700 | const ASTContext &C = Context; |
| 2701 | return new (C) concepts::Requirement::SubstitutionDiagnostic{ |
| 2702 | /*SubstitutedEntity=*/C.backupStr(S: Entity), |
| 2703 | /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()}; |
| 2704 | } |
| 2705 | |
| 2706 | ExprResult TemplateInstantiator::TransformRequiresTypeParams( |
| 2707 | SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, |
| 2708 | RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, |
| 2709 | SmallVectorImpl<QualType> &PTypes, |
| 2710 | SmallVectorImpl<ParmVarDecl *> &TransParams, |
| 2711 | Sema::ExtParameterInfoBuilder &PInfos) { |
| 2712 | |
| 2713 | TemplateDeductionInfo Info(KWLoc); |
| 2714 | Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE, |
| 2715 | SourceRange{KWLoc, RBraceLoc}); |
| 2716 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2717 | |
| 2718 | unsigned ErrorIdx; |
| 2719 | if (getDerived().TransformFunctionTypeParams( |
| 2720 | Loc: KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, OutParamTypes&: PTypes, |
| 2721 | PVars: &TransParams, PInfos, LastParamTransformed: &ErrorIdx) || |
| 2722 | Trap.hasErrorOccurred()) { |
| 2723 | SmallVector<concepts::Requirement *, 4> TransReqs; |
| 2724 | ParmVarDecl *FailedDecl = Params[ErrorIdx]; |
| 2725 | // Add a 'failed' Requirement to contain the error that caused the failure |
| 2726 | // here. |
| 2727 | TransReqs.push_back(Elt: RebuildTypeRequirement(SubstDiag: createSubstDiag( |
| 2728 | S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) { OS << *FailedDecl; }))); |
| 2729 | return getDerived().RebuildRequiresExpr(RequiresKWLoc: KWLoc, Body, LParenLoc: RE->getLParenLoc(), |
| 2730 | LocalParameters: TransParams, RParenLoc: RE->getRParenLoc(), |
| 2731 | Requirements: TransReqs, ClosingBraceLoc: RBraceLoc); |
| 2732 | } |
| 2733 | |
| 2734 | return ExprResult{}; |
| 2735 | } |
| 2736 | |
| 2737 | concepts::TypeRequirement * |
| 2738 | TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) { |
| 2739 | if (!Req->isDependent() && !AlwaysRebuild()) |
| 2740 | return Req; |
| 2741 | if (Req->isSubstitutionFailure()) { |
| 2742 | if (AlwaysRebuild()) |
| 2743 | return RebuildTypeRequirement( |
| 2744 | SubstDiag: Req->getSubstitutionDiagnostic()); |
| 2745 | return Req; |
| 2746 | } |
| 2747 | |
| 2748 | TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc()); |
| 2749 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2750 | Sema::InstantiatingTemplate TypeInst( |
| 2751 | SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req, |
| 2752 | Req->getType()->getTypeLoc().getSourceRange()); |
| 2753 | if (TypeInst.isInvalid()) |
| 2754 | return nullptr; |
| 2755 | TypeSourceInfo *TransType = TransformType(TSI: Req->getType()); |
| 2756 | if (!TransType || Trap.hasErrorOccurred()) |
| 2757 | return RebuildTypeRequirement(SubstDiag: createSubstDiag(S&: SemaRef, Info, |
| 2758 | Printer: [&] (llvm::raw_ostream& OS) { |
| 2759 | Req->getType()->getType().print(OS, Policy: SemaRef.getPrintingPolicy()); |
| 2760 | })); |
| 2761 | return RebuildTypeRequirement(T: TransType); |
| 2762 | } |
| 2763 | |
| 2764 | concepts::ExprRequirement * |
| 2765 | TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { |
| 2766 | if (!Req->isDependent() && !AlwaysRebuild()) |
| 2767 | return Req; |
| 2768 | |
| 2769 | llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> |
| 2770 | TransExpr; |
| 2771 | if (Req->isExprSubstitutionFailure()) |
| 2772 | TransExpr = Req->getExprSubstitutionDiagnostic(); |
| 2773 | else { |
| 2774 | Expr *E = Req->getExpr(); |
| 2775 | TemplateDeductionInfo Info(E->getBeginLoc()); |
| 2776 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2777 | Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, |
| 2778 | E->getSourceRange()); |
| 2779 | if (ExprInst.isInvalid()) |
| 2780 | return nullptr; |
| 2781 | ExprResult TransExprRes = TransformExpr(E); |
| 2782 | if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() && |
| 2783 | TransExprRes.get()->hasPlaceholderType()) |
| 2784 | TransExprRes = SemaRef.CheckPlaceholderExpr(E: TransExprRes.get()); |
| 2785 | if (TransExprRes.isInvalid() || Trap.hasErrorOccurred()) |
| 2786 | TransExpr = createSubstDiag(S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) { |
| 2787 | E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy()); |
| 2788 | }); |
| 2789 | else |
| 2790 | TransExpr = TransExprRes.get(); |
| 2791 | } |
| 2792 | |
| 2793 | std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; |
| 2794 | const auto &RetReq = Req->getReturnTypeRequirement(); |
| 2795 | if (RetReq.isEmpty()) |
| 2796 | TransRetReq.emplace(); |
| 2797 | else if (RetReq.isSubstitutionFailure()) |
| 2798 | TransRetReq.emplace(args: RetReq.getSubstitutionDiagnostic()); |
| 2799 | else if (RetReq.isTypeConstraint()) { |
| 2800 | TemplateParameterList *OrigTPL = |
| 2801 | RetReq.getTypeConstraintTemplateParameterList(); |
| 2802 | TemplateDeductionInfo Info(OrigTPL->getTemplateLoc()); |
| 2803 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2804 | Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req, |
| 2805 | OrigTPL->getSourceRange()); |
| 2806 | if (TPLInst.isInvalid()) |
| 2807 | return nullptr; |
| 2808 | TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL); |
| 2809 | if (!TPL || Trap.hasErrorOccurred()) |
| 2810 | TransRetReq.emplace(args: createSubstDiag(S&: SemaRef, Info, |
| 2811 | Printer: [&] (llvm::raw_ostream& OS) { |
| 2812 | RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint() |
| 2813 | ->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy()); |
| 2814 | })); |
| 2815 | else { |
| 2816 | TPLInst.Clear(); |
| 2817 | TransRetReq.emplace(args&: TPL); |
| 2818 | } |
| 2819 | } |
| 2820 | assert(TransRetReq && "All code paths leading here must set TransRetReq" ); |
| 2821 | if (Expr *E = TransExpr.dyn_cast<Expr *>()) |
| 2822 | return RebuildExprRequirement(E, IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(), |
| 2823 | Ret: std::move(*TransRetReq)); |
| 2824 | return RebuildExprRequirement( |
| 2825 | SubstDiag: cast<concepts::Requirement::SubstitutionDiagnostic *>(Val&: TransExpr), |
| 2826 | IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(), Ret: std::move(*TransRetReq)); |
| 2827 | } |
| 2828 | |
| 2829 | concepts::NestedRequirement * |
| 2830 | TemplateInstantiator::TransformNestedRequirement( |
| 2831 | concepts::NestedRequirement *Req) { |
| 2832 | |
| 2833 | ASTContext &C = SemaRef.Context; |
| 2834 | |
| 2835 | Expr *Constraint = Req->getConstraintExpr(); |
| 2836 | ConstraintSatisfaction Satisfaction; |
| 2837 | |
| 2838 | auto NestedReqWithDiag = [&C, this](Expr *E, |
| 2839 | ConstraintSatisfaction Satisfaction) { |
| 2840 | Satisfaction.IsSatisfied = false; |
| 2841 | SmallString<128> Entity; |
| 2842 | llvm::raw_svector_ostream OS(Entity); |
| 2843 | E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy()); |
| 2844 | return new (C) concepts::NestedRequirement( |
| 2845 | SemaRef.Context, C.backupStr(S: Entity), std::move(Satisfaction)); |
| 2846 | }; |
| 2847 | |
| 2848 | if (Req->hasInvalidConstraint()) { |
| 2849 | if (AlwaysRebuild()) |
| 2850 | return RebuildNestedRequirement(InvalidConstraintEntity: Req->getInvalidConstraintEntity(), |
| 2851 | Satisfaction: Req->getConstraintSatisfaction()); |
| 2852 | return Req; |
| 2853 | } |
| 2854 | |
| 2855 | if (!getEvaluateConstraints()) { |
| 2856 | ExprResult TransConstraint = TransformExpr(E: Req->getConstraintExpr()); |
| 2857 | if (TransConstraint.isInvalid() || !TransConstraint.get()) |
| 2858 | return nullptr; |
| 2859 | if (TransConstraint.get()->isInstantiationDependent()) |
| 2860 | return new (SemaRef.Context) |
| 2861 | concepts::NestedRequirement(TransConstraint.get()); |
| 2862 | ConstraintSatisfaction Satisfaction; |
| 2863 | return new (SemaRef.Context) concepts::NestedRequirement( |
| 2864 | SemaRef.Context, TransConstraint.get(), Satisfaction); |
| 2865 | } |
| 2866 | |
| 2867 | bool Success; |
| 2868 | Expr *NewConstraint; |
| 2869 | { |
| 2870 | EnterExpressionEvaluationContext ( |
| 2871 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
| 2872 | Sema::InstantiatingTemplate ConstrInst( |
| 2873 | SemaRef, Constraint->getBeginLoc(), Req, |
| 2874 | Sema::InstantiatingTemplate::ConstraintsCheck(), |
| 2875 | Constraint->getSourceRange()); |
| 2876 | |
| 2877 | if (ConstrInst.isInvalid()) |
| 2878 | return nullptr; |
| 2879 | |
| 2880 | Success = !SemaRef.CheckConstraintSatisfaction( |
| 2881 | Entity: Req, AssociatedConstraints: AssociatedConstraint(Constraint), TemplateArgLists: TemplateArgs, |
| 2882 | TemplateIDRange: Constraint->getSourceRange(), Satisfaction, |
| 2883 | /*TopLevelConceptId=*/nullptr, ConvertedExpr: &NewConstraint); |
| 2884 | } |
| 2885 | |
| 2886 | if (!Success || Satisfaction.HasSubstitutionFailure()) |
| 2887 | return NestedReqWithDiag(Constraint, Satisfaction); |
| 2888 | |
| 2889 | // FIXME: const correctness |
| 2890 | // MLTAL might be dependent. |
| 2891 | if (!NewConstraint) { |
| 2892 | if (!Satisfaction.IsSatisfied) |
| 2893 | return NestedReqWithDiag(Constraint, Satisfaction); |
| 2894 | |
| 2895 | NewConstraint = Constraint; |
| 2896 | } |
| 2897 | return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction); |
| 2898 | } |
| 2899 | |
| 2900 | TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, |
| 2901 | const MultiLevelTemplateArgumentList &Args, |
| 2902 | SourceLocation Loc, DeclarationName Entity, |
| 2903 | bool AllowDeducedTST) { |
| 2904 | if (!T->getType()->isInstantiationDependentType() && |
| 2905 | !T->getType()->isVariablyModifiedType()) |
| 2906 | return T; |
| 2907 | |
| 2908 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
| 2909 | return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(TSI: T) |
| 2910 | : Instantiator.TransformType(TSI: T); |
| 2911 | } |
| 2912 | |
| 2913 | TypeSourceInfo *Sema::SubstType(TypeLoc TL, |
| 2914 | const MultiLevelTemplateArgumentList &Args, |
| 2915 | SourceLocation Loc, DeclarationName Entity) { |
| 2916 | if (TL.getType().isNull()) |
| 2917 | return nullptr; |
| 2918 | |
| 2919 | if (!TL.getType()->isInstantiationDependentType() && |
| 2920 | !TL.getType()->isVariablyModifiedType()) { |
| 2921 | // FIXME: Make a copy of the TypeLoc data here, so that we can |
| 2922 | // return a new TypeSourceInfo. Inefficient! |
| 2923 | TypeLocBuilder TLB; |
| 2924 | TLB.pushFullCopy(L: TL); |
| 2925 | return TLB.getTypeSourceInfo(Context, T: TL.getType()); |
| 2926 | } |
| 2927 | |
| 2928 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
| 2929 | TypeLocBuilder TLB; |
| 2930 | TLB.reserve(Requested: TL.getFullDataSize()); |
| 2931 | QualType Result = Instantiator.TransformType(TLB, T: TL); |
| 2932 | if (Result.isNull()) |
| 2933 | return nullptr; |
| 2934 | |
| 2935 | return TLB.getTypeSourceInfo(Context, T: Result); |
| 2936 | } |
| 2937 | |
| 2938 | /// Deprecated form of the above. |
| 2939 | QualType Sema::SubstType(QualType T, |
| 2940 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 2941 | SourceLocation Loc, DeclarationName Entity, |
| 2942 | bool *IsIncompleteSubstitution) { |
| 2943 | // If T is not a dependent type or a variably-modified type, there |
| 2944 | // is nothing to do. |
| 2945 | if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType()) |
| 2946 | return T; |
| 2947 | |
| 2948 | TemplateInstantiator Instantiator( |
| 2949 | *this, TemplateArgs, Loc, Entity, |
| 2950 | /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr); |
| 2951 | QualType QT = Instantiator.TransformType(T); |
| 2952 | if (IsIncompleteSubstitution && Instantiator.getIsIncomplete()) |
| 2953 | *IsIncompleteSubstitution = true; |
| 2954 | return QT; |
| 2955 | } |
| 2956 | |
| 2957 | static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { |
| 2958 | if (T->getType()->isInstantiationDependentType() || |
| 2959 | T->getType()->isVariablyModifiedType()) |
| 2960 | return true; |
| 2961 | |
| 2962 | TypeLoc TL = T->getTypeLoc().IgnoreParens(); |
| 2963 | if (!TL.getAs<FunctionProtoTypeLoc>()) |
| 2964 | return false; |
| 2965 | |
| 2966 | FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>(); |
| 2967 | for (ParmVarDecl *P : FP.getParams()) { |
| 2968 | // This must be synthesized from a typedef. |
| 2969 | if (!P) continue; |
| 2970 | |
| 2971 | // If there are any parameters, a new TypeSourceInfo that refers to the |
| 2972 | // instantiated parameters must be built. |
| 2973 | return true; |
| 2974 | } |
| 2975 | |
| 2976 | return false; |
| 2977 | } |
| 2978 | |
| 2979 | TypeSourceInfo *Sema::SubstFunctionDeclType( |
| 2980 | TypeSourceInfo *T, const MultiLevelTemplateArgumentList &Args, |
| 2981 | SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, |
| 2982 | Qualifiers ThisTypeQuals, bool EvaluateConstraints) { |
| 2983 | if (!NeedsInstantiationAsFunctionType(T)) |
| 2984 | return T; |
| 2985 | |
| 2986 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
| 2987 | Instantiator.setEvaluateConstraints(EvaluateConstraints); |
| 2988 | |
| 2989 | TypeLocBuilder TLB; |
| 2990 | |
| 2991 | TypeLoc TL = T->getTypeLoc(); |
| 2992 | TLB.reserve(Requested: TL.getFullDataSize()); |
| 2993 | |
| 2994 | QualType Result; |
| 2995 | |
| 2996 | if (FunctionProtoTypeLoc Proto = |
| 2997 | TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) { |
| 2998 | // Instantiate the type, other than its exception specification. The |
| 2999 | // exception specification is instantiated in InitFunctionInstantiation |
| 3000 | // once we've built the FunctionDecl. |
| 3001 | // FIXME: Set the exception specification to EST_Uninstantiated here, |
| 3002 | // instead of rebuilding the function type again later. |
| 3003 | Result = Instantiator.TransformFunctionProtoType( |
| 3004 | TLB, TL: Proto, ThisContext, ThisTypeQuals, |
| 3005 | TransformExceptionSpec: [](FunctionProtoType::ExceptionSpecInfo &ESI, |
| 3006 | bool &Changed) { return false; }); |
| 3007 | } else { |
| 3008 | Result = Instantiator.TransformType(TLB, T: TL); |
| 3009 | } |
| 3010 | // When there are errors resolving types, clang may use IntTy as a fallback, |
| 3011 | // breaking our assumption that function declarations have function types. |
| 3012 | if (Result.isNull() || !Result->isFunctionType()) |
| 3013 | return nullptr; |
| 3014 | |
| 3015 | return TLB.getTypeSourceInfo(Context, T: Result); |
| 3016 | } |
| 3017 | |
| 3018 | bool Sema::SubstExceptionSpec(SourceLocation Loc, |
| 3019 | FunctionProtoType::ExceptionSpecInfo &ESI, |
| 3020 | SmallVectorImpl<QualType> &ExceptionStorage, |
| 3021 | const MultiLevelTemplateArgumentList &Args) { |
| 3022 | bool Changed = false; |
| 3023 | TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName()); |
| 3024 | return Instantiator.TransformExceptionSpec(Loc, ESI, Exceptions&: ExceptionStorage, |
| 3025 | Changed); |
| 3026 | } |
| 3027 | |
| 3028 | void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, |
| 3029 | const MultiLevelTemplateArgumentList &Args) { |
| 3030 | FunctionProtoType::ExceptionSpecInfo ESI = |
| 3031 | Proto->getExtProtoInfo().ExceptionSpec; |
| 3032 | |
| 3033 | SmallVector<QualType, 4> ExceptionStorage; |
| 3034 | if (SubstExceptionSpec(Loc: New->getTypeSourceInfo()->getTypeLoc().getEndLoc(), |
| 3035 | ESI, ExceptionStorage, Args)) |
| 3036 | // On error, recover by dropping the exception specification. |
| 3037 | ESI.Type = EST_None; |
| 3038 | |
| 3039 | UpdateExceptionSpec(FD: New, ESI); |
| 3040 | } |
| 3041 | |
| 3042 | namespace { |
| 3043 | |
| 3044 | struct GetContainedInventedTypeParmVisitor : |
| 3045 | public TypeVisitor<GetContainedInventedTypeParmVisitor, |
| 3046 | TemplateTypeParmDecl *> { |
| 3047 | using TypeVisitor<GetContainedInventedTypeParmVisitor, |
| 3048 | TemplateTypeParmDecl *>::Visit; |
| 3049 | |
| 3050 | TemplateTypeParmDecl *Visit(QualType T) { |
| 3051 | if (T.isNull()) |
| 3052 | return nullptr; |
| 3053 | return Visit(T: T.getTypePtr()); |
| 3054 | } |
| 3055 | // The deduced type itself. |
| 3056 | TemplateTypeParmDecl *VisitTemplateTypeParmType( |
| 3057 | const TemplateTypeParmType *T) { |
| 3058 | if (!T->getDecl() || !T->getDecl()->isImplicit()) |
| 3059 | return nullptr; |
| 3060 | return T->getDecl(); |
| 3061 | } |
| 3062 | |
| 3063 | // Only these types can contain 'auto' types, and subsequently be replaced |
| 3064 | // by references to invented parameters. |
| 3065 | |
| 3066 | TemplateTypeParmDecl *VisitPointerType(const PointerType *T) { |
| 3067 | return Visit(T: T->getPointeeType()); |
| 3068 | } |
| 3069 | |
| 3070 | TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) { |
| 3071 | return Visit(T: T->getPointeeType()); |
| 3072 | } |
| 3073 | |
| 3074 | TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) { |
| 3075 | return Visit(T: T->getPointeeTypeAsWritten()); |
| 3076 | } |
| 3077 | |
| 3078 | TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) { |
| 3079 | return Visit(T: T->getPointeeType()); |
| 3080 | } |
| 3081 | |
| 3082 | TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) { |
| 3083 | return Visit(T: T->getElementType()); |
| 3084 | } |
| 3085 | |
| 3086 | TemplateTypeParmDecl *VisitDependentSizedExtVectorType( |
| 3087 | const DependentSizedExtVectorType *T) { |
| 3088 | return Visit(T: T->getElementType()); |
| 3089 | } |
| 3090 | |
| 3091 | TemplateTypeParmDecl *VisitVectorType(const VectorType *T) { |
| 3092 | return Visit(T: T->getElementType()); |
| 3093 | } |
| 3094 | |
| 3095 | TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) { |
| 3096 | return VisitFunctionType(T); |
| 3097 | } |
| 3098 | |
| 3099 | TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) { |
| 3100 | return Visit(T: T->getReturnType()); |
| 3101 | } |
| 3102 | |
| 3103 | TemplateTypeParmDecl *VisitParenType(const ParenType *T) { |
| 3104 | return Visit(T: T->getInnerType()); |
| 3105 | } |
| 3106 | |
| 3107 | TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) { |
| 3108 | return Visit(T: T->getModifiedType()); |
| 3109 | } |
| 3110 | |
| 3111 | TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) { |
| 3112 | return Visit(T: T->getUnderlyingType()); |
| 3113 | } |
| 3114 | |
| 3115 | TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) { |
| 3116 | return Visit(T: T->getOriginalType()); |
| 3117 | } |
| 3118 | |
| 3119 | TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) { |
| 3120 | return Visit(T: T->getPattern()); |
| 3121 | } |
| 3122 | }; |
| 3123 | |
| 3124 | } // namespace |
| 3125 | |
| 3126 | bool Sema::SubstTypeConstraint( |
| 3127 | TemplateTypeParmDecl *Inst, const TypeConstraint *TC, |
| 3128 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3129 | bool EvaluateConstraints) { |
| 3130 | const ASTTemplateArgumentListInfo *TemplArgInfo = |
| 3131 | TC->getTemplateArgsAsWritten(); |
| 3132 | |
| 3133 | if (!EvaluateConstraints) { |
| 3134 | UnsignedOrNone Index = TC->getArgPackSubstIndex(); |
| 3135 | bool ContainsUnexpandedPack = |
| 3136 | TemplArgInfo && |
| 3137 | llvm::any_of( |
| 3138 | Range: TemplArgInfo->arguments(), P: [](const TemplateArgumentLoc &TA) { |
| 3139 | return TA.getArgument().containsUnexpandedParameterPack(); |
| 3140 | }); |
| 3141 | if (!Index && ContainsUnexpandedPack) |
| 3142 | Index = SemaRef.ArgPackSubstIndex; |
| 3143 | Inst->setTypeConstraint(CR: TC->getConceptReference(), |
| 3144 | ImmediatelyDeclaredConstraint: TC->getImmediatelyDeclaredConstraint(), ArgPackSubstIndex: Index); |
| 3145 | return false; |
| 3146 | } |
| 3147 | |
| 3148 | TemplateArgumentListInfo InstArgs; |
| 3149 | |
| 3150 | if (TemplArgInfo) { |
| 3151 | InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc); |
| 3152 | InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc); |
| 3153 | if (SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs, |
| 3154 | Outputs&: InstArgs)) |
| 3155 | return true; |
| 3156 | } |
| 3157 | return AttachTypeConstraint( |
| 3158 | NS: TC->getNestedNameSpecifierLoc(), NameInfo: TC->getConceptNameInfo(), |
| 3159 | NamedConcept: TC->getNamedConcept(), |
| 3160 | /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), TemplateArgs: &InstArgs, ConstrainedParameter: Inst, |
| 3161 | EllipsisLoc: Inst->isParameterPack() |
| 3162 | ? cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint()) |
| 3163 | ->getEllipsisLoc() |
| 3164 | : SourceLocation()); |
| 3165 | } |
| 3166 | |
| 3167 | ParmVarDecl * |
| 3168 | Sema::SubstParmVarDecl(ParmVarDecl *OldParm, |
| 3169 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3170 | int indexAdjustment, UnsignedOrNone NumExpansions, |
| 3171 | bool ExpectParameterPack, bool EvaluateConstraint) { |
| 3172 | TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo(); |
| 3173 | TypeSourceInfo *NewTSI = nullptr; |
| 3174 | |
| 3175 | TypeLoc OldTL = OldTSI->getTypeLoc(); |
| 3176 | if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { |
| 3177 | |
| 3178 | // We have a function parameter pack. Substitute into the pattern of the |
| 3179 | // expansion. |
| 3180 | NewTSI = SubstType(TL: ExpansionTL.getPatternLoc(), Args: TemplateArgs, |
| 3181 | Loc: OldParm->getLocation(), Entity: OldParm->getDeclName()); |
| 3182 | if (!NewTSI) |
| 3183 | return nullptr; |
| 3184 | |
| 3185 | if (NewTSI->getType()->containsUnexpandedParameterPack()) { |
| 3186 | // We still have unexpanded parameter packs, which means that |
| 3187 | // our function parameter is still a function parameter pack. |
| 3188 | // Therefore, make its type a pack expansion type. |
| 3189 | NewTSI = CheckPackExpansion(Pattern: NewTSI, EllipsisLoc: ExpansionTL.getEllipsisLoc(), |
| 3190 | NumExpansions); |
| 3191 | } else if (ExpectParameterPack) { |
| 3192 | // We expected to get a parameter pack but didn't (because the type |
| 3193 | // itself is not a pack expansion type), so complain. This can occur when |
| 3194 | // the substitution goes through an alias template that "loses" the |
| 3195 | // pack expansion. |
| 3196 | Diag(Loc: OldParm->getLocation(), |
| 3197 | DiagID: diag::err_function_parameter_pack_without_parameter_packs) |
| 3198 | << NewTSI->getType(); |
| 3199 | return nullptr; |
| 3200 | } |
| 3201 | } else { |
| 3202 | NewTSI = SubstType(T: OldTSI, Args: TemplateArgs, Loc: OldParm->getLocation(), |
| 3203 | Entity: OldParm->getDeclName()); |
| 3204 | } |
| 3205 | |
| 3206 | if (!NewTSI) |
| 3207 | return nullptr; |
| 3208 | |
| 3209 | if (NewTSI->getType()->isVoidType()) { |
| 3210 | Diag(Loc: OldParm->getLocation(), DiagID: diag::err_param_with_void_type); |
| 3211 | return nullptr; |
| 3212 | } |
| 3213 | |
| 3214 | // In abbreviated templates, TemplateTypeParmDecls with possible |
| 3215 | // TypeConstraints are created when the parameter list is originally parsed. |
| 3216 | // The TypeConstraints can therefore reference other functions parameters in |
| 3217 | // the abbreviated function template, which is why we must instantiate them |
| 3218 | // here, when the instantiated versions of those referenced parameters are in |
| 3219 | // scope. |
| 3220 | if (TemplateTypeParmDecl *TTP = |
| 3221 | GetContainedInventedTypeParmVisitor().Visit(T: OldTSI->getType())) { |
| 3222 | if (const TypeConstraint *TC = TTP->getTypeConstraint()) { |
| 3223 | auto *Inst = cast_or_null<TemplateTypeParmDecl>( |
| 3224 | Val: FindInstantiatedDecl(Loc: TTP->getLocation(), D: TTP, TemplateArgs)); |
| 3225 | // We will first get here when instantiating the abbreviated function |
| 3226 | // template's described function, but we might also get here later. |
| 3227 | // Make sure we do not instantiate the TypeConstraint more than once. |
| 3228 | if (Inst && !Inst->getTypeConstraint()) { |
| 3229 | if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraints: EvaluateConstraint)) |
| 3230 | return nullptr; |
| 3231 | } |
| 3232 | } |
| 3233 | } |
| 3234 | |
| 3235 | ParmVarDecl *NewParm = CheckParameter( |
| 3236 | DC: Context.getTranslationUnitDecl(), StartLoc: OldParm->getInnerLocStart(), |
| 3237 | NameLoc: OldParm->getLocation(), Name: OldParm->getIdentifier(), T: NewTSI->getType(), |
| 3238 | TSInfo: NewTSI, SC: OldParm->getStorageClass()); |
| 3239 | if (!NewParm) |
| 3240 | return nullptr; |
| 3241 | |
| 3242 | // Mark the (new) default argument as uninstantiated (if any). |
| 3243 | if (OldParm->hasUninstantiatedDefaultArg()) { |
| 3244 | Expr *Arg = OldParm->getUninstantiatedDefaultArg(); |
| 3245 | NewParm->setUninstantiatedDefaultArg(Arg); |
| 3246 | } else if (OldParm->hasUnparsedDefaultArg()) { |
| 3247 | NewParm->setUnparsedDefaultArg(); |
| 3248 | UnparsedDefaultArgInstantiations[OldParm].push_back(NewVal: NewParm); |
| 3249 | } else if (Expr *Arg = OldParm->getDefaultArg()) { |
| 3250 | // Default arguments cannot be substituted until the declaration context |
| 3251 | // for the associated function or lambda capture class is available. |
| 3252 | // This is necessary for cases like the following where construction of |
| 3253 | // the lambda capture class for the outer lambda is dependent on the |
| 3254 | // parameter types but where the default argument is dependent on the |
| 3255 | // outer lambda's declaration context. |
| 3256 | // template <typename T> |
| 3257 | // auto f() { |
| 3258 | // return [](T = []{ return T{}; }()) { return 0; }; |
| 3259 | // } |
| 3260 | NewParm->setUninstantiatedDefaultArg(Arg); |
| 3261 | } |
| 3262 | |
| 3263 | NewParm->setExplicitObjectParameterLoc( |
| 3264 | OldParm->getExplicitObjectParamThisLoc()); |
| 3265 | NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); |
| 3266 | |
| 3267 | if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { |
| 3268 | // Add the new parameter to the instantiated parameter pack. |
| 3269 | CurrentInstantiationScope->InstantiatedLocalPackArg(D: OldParm, Inst: NewParm); |
| 3270 | } else { |
| 3271 | // Introduce an Old -> New mapping |
| 3272 | CurrentInstantiationScope->InstantiatedLocal(D: OldParm, Inst: NewParm); |
| 3273 | } |
| 3274 | |
| 3275 | // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext |
| 3276 | // can be anything, is this right ? |
| 3277 | NewParm->setDeclContext(CurContext); |
| 3278 | |
| 3279 | NewParm->setScopeInfo(scopeDepth: OldParm->getFunctionScopeDepth(), |
| 3280 | parameterIndex: OldParm->getFunctionScopeIndex() + indexAdjustment); |
| 3281 | |
| 3282 | InstantiateAttrs(TemplateArgs, Pattern: OldParm, Inst: NewParm); |
| 3283 | |
| 3284 | NewParm->deduceParmAddressSpace(Ctxt: Context); |
| 3285 | |
| 3286 | return NewParm; |
| 3287 | } |
| 3288 | |
| 3289 | bool Sema::SubstParmTypes( |
| 3290 | SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, |
| 3291 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, |
| 3292 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3293 | SmallVectorImpl<QualType> &ParamTypes, |
| 3294 | SmallVectorImpl<ParmVarDecl *> *OutParams, |
| 3295 | ExtParameterInfoBuilder &ParamInfos) { |
| 3296 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, |
| 3297 | DeclarationName()); |
| 3298 | return Instantiator.TransformFunctionTypeParams( |
| 3299 | Loc, Params, ParamTypes: nullptr, ParamInfos: ExtParamInfos, PTypes&: ParamTypes, PVars: OutParams, PInfos&: ParamInfos); |
| 3300 | } |
| 3301 | |
| 3302 | bool Sema::SubstDefaultArgument( |
| 3303 | SourceLocation Loc, |
| 3304 | ParmVarDecl *Param, |
| 3305 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3306 | bool ForCallExpr) { |
| 3307 | FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext()); |
| 3308 | Expr *PatternExpr = Param->getUninstantiatedDefaultArg(); |
| 3309 | |
| 3310 | RecursiveInstGuard AlreadyInstantiating( |
| 3311 | *this, Param, RecursiveInstGuard::Kind::DefaultArgument); |
| 3312 | if (AlreadyInstantiating) { |
| 3313 | Param->setInvalidDecl(); |
| 3314 | return Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) |
| 3315 | << FD << PatternExpr->getSourceRange(); |
| 3316 | } |
| 3317 | |
| 3318 | EnterExpressionEvaluationContext EvalContext( |
| 3319 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); |
| 3320 | NonSFINAEContext _(*this); |
| 3321 | InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost()); |
| 3322 | if (Inst.isInvalid()) |
| 3323 | return true; |
| 3324 | |
| 3325 | ExprResult Result; |
| 3326 | // C++ [dcl.fct.default]p5: |
| 3327 | // The names in the [default argument] expression are bound, and |
| 3328 | // the semantic constraints are checked, at the point where the |
| 3329 | // default argument expression appears. |
| 3330 | ContextRAII SavedContext(*this, FD); |
| 3331 | { |
| 3332 | std::optional<LocalInstantiationScope> LIS; |
| 3333 | |
| 3334 | if (ForCallExpr) { |
| 3335 | // When instantiating a default argument due to use in a call expression, |
| 3336 | // an instantiation scope that includes the parameters of the callee is |
| 3337 | // required to satisfy references from the default argument. For example: |
| 3338 | // template<typename T> void f(T a, int = decltype(a)()); |
| 3339 | // void g() { f(0); } |
| 3340 | LIS.emplace(args&: *this); |
| 3341 | FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern( |
| 3342 | /*ForDefinition*/ false); |
| 3343 | if (addInstantiatedParametersToScope(Function: FD, PatternDecl: PatternFD, Scope&: *LIS, TemplateArgs)) |
| 3344 | return true; |
| 3345 | } |
| 3346 | |
| 3347 | runWithSufficientStackSpace(Loc, Fn: [&] { |
| 3348 | Result = SubstInitializer(E: PatternExpr, TemplateArgs, |
| 3349 | /*DirectInit*/ CXXDirectInit: false); |
| 3350 | }); |
| 3351 | } |
| 3352 | if (Result.isInvalid()) |
| 3353 | return true; |
| 3354 | |
| 3355 | if (ForCallExpr) { |
| 3356 | // Check the expression as an initializer for the parameter. |
| 3357 | InitializedEntity Entity |
| 3358 | = InitializedEntity::InitializeParameter(Context, Parm: Param); |
| 3359 | InitializationKind Kind = InitializationKind::CreateCopy( |
| 3360 | InitLoc: Param->getLocation(), |
| 3361 | /*FIXME:EqualLoc*/ EqualLoc: PatternExpr->getBeginLoc()); |
| 3362 | Expr *ResultE = Result.getAs<Expr>(); |
| 3363 | |
| 3364 | InitializationSequence InitSeq(*this, Entity, Kind, ResultE); |
| 3365 | Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: ResultE); |
| 3366 | if (Result.isInvalid()) |
| 3367 | return true; |
| 3368 | |
| 3369 | Result = |
| 3370 | ActOnFinishFullExpr(Expr: Result.getAs<Expr>(), CC: Param->getOuterLocStart(), |
| 3371 | /*DiscardedValue*/ false); |
| 3372 | } else { |
| 3373 | // FIXME: Obtain the source location for the '=' token. |
| 3374 | SourceLocation EqualLoc = PatternExpr->getBeginLoc(); |
| 3375 | Result = ConvertParamDefaultArgument(Param, DefaultArg: Result.getAs<Expr>(), EqualLoc); |
| 3376 | } |
| 3377 | if (Result.isInvalid()) |
| 3378 | return true; |
| 3379 | |
| 3380 | // Remember the instantiated default argument. |
| 3381 | Param->setDefaultArg(Result.getAs<Expr>()); |
| 3382 | |
| 3383 | return false; |
| 3384 | } |
| 3385 | |
| 3386 | // See TreeTransform::PreparePackForExpansion for the relevant comment. |
| 3387 | // This function implements the same concept for base specifiers. |
| 3388 | static bool |
| 3389 | PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base, |
| 3390 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3391 | TypeSourceInfo *&Out, UnexpandedInfo &Info) { |
| 3392 | SourceRange BaseSourceRange = Base.getSourceRange(); |
| 3393 | SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc(); |
| 3394 | Info.Ellipsis = Base.getEllipsisLoc(); |
| 3395 | auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc]( |
| 3396 | TypeSourceInfo *BaseTypeInfo, |
| 3397 | bool IsLateExpansionAttempt, UnexpandedInfo &Info) { |
| 3398 | // This is a pack expansion. See whether we should expand it now, or |
| 3399 | // wait until later. |
| 3400 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
| 3401 | S.collectUnexpandedParameterPacks(TL: BaseTypeInfo->getTypeLoc(), Unexpanded); |
| 3402 | if (IsLateExpansionAttempt) { |
| 3403 | // Request expansion only when there is an opportunity to expand a pack |
| 3404 | // that required a substituion first. |
| 3405 | bool SawPackTypes = |
| 3406 | llvm::any_of(Range&: Unexpanded, P: [](UnexpandedParameterPack P) { |
| 3407 | return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>(); |
| 3408 | }); |
| 3409 | if (!SawPackTypes) { |
| 3410 | Info.Expand = false; |
| 3411 | return false; |
| 3412 | } |
| 3413 | } |
| 3414 | |
| 3415 | // Determine whether the set of unexpanded parameter packs can and should be |
| 3416 | // expanded. |
| 3417 | Info.Expand = false; |
| 3418 | Info.RetainExpansion = false; |
| 3419 | Info.NumExpansions = std::nullopt; |
| 3420 | return S.CheckParameterPacksForExpansion( |
| 3421 | EllipsisLoc: BaseEllipsisLoc, PatternRange: BaseSourceRange, Unexpanded, TemplateArgs, |
| 3422 | /*FailOnPackProducingTemplates=*/false, ShouldExpand&: Info.Expand, |
| 3423 | RetainExpansion&: Info.RetainExpansion, NumExpansions&: Info.NumExpansions); |
| 3424 | }; |
| 3425 | |
| 3426 | if (ComputeInfo(Base.getTypeSourceInfo(), false, Info)) |
| 3427 | return true; |
| 3428 | |
| 3429 | if (Info.Expand) { |
| 3430 | Out = Base.getTypeSourceInfo(); |
| 3431 | return false; |
| 3432 | } |
| 3433 | |
| 3434 | // The resulting base specifier will (still) be a pack expansion. |
| 3435 | { |
| 3436 | Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt); |
| 3437 | Out = S.SubstType(T: Base.getTypeSourceInfo(), Args: TemplateArgs, |
| 3438 | Loc: BaseSourceRange.getBegin(), Entity: DeclarationName()); |
| 3439 | } |
| 3440 | if (!Out->getType()->containsUnexpandedParameterPack()) |
| 3441 | return false; |
| 3442 | |
| 3443 | // Some packs will learn their length after substitution. |
| 3444 | // We may need to request their expansion. |
| 3445 | if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info)) |
| 3446 | return true; |
| 3447 | if (Info.Expand) |
| 3448 | Info.ExpandUnderForgetSubstitions = true; |
| 3449 | return false; |
| 3450 | } |
| 3451 | |
| 3452 | bool |
| 3453 | Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, |
| 3454 | CXXRecordDecl *Pattern, |
| 3455 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 3456 | bool Invalid = false; |
| 3457 | SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; |
| 3458 | for (const auto &Base : Pattern->bases()) { |
| 3459 | if (!Base.getType()->isInstantiationDependentType()) { |
| 3460 | if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) { |
| 3461 | if (RD->isInvalidDecl()) |
| 3462 | Instantiation->setInvalidDecl(); |
| 3463 | } |
| 3464 | InstantiatedBases.push_back(Elt: new (Context) CXXBaseSpecifier(Base)); |
| 3465 | continue; |
| 3466 | } |
| 3467 | |
| 3468 | SourceLocation EllipsisLoc; |
| 3469 | TypeSourceInfo *BaseTypeLoc = nullptr; |
| 3470 | if (Base.isPackExpansion()) { |
| 3471 | UnexpandedInfo Info; |
| 3472 | if (PreparePackForExpansion(S&: *this, Base, TemplateArgs, Out&: BaseTypeLoc, |
| 3473 | Info)) { |
| 3474 | Invalid = true; |
| 3475 | continue; |
| 3476 | } |
| 3477 | |
| 3478 | // If we should expand this pack expansion now, do so. |
| 3479 | MultiLevelTemplateArgumentList EmptyList; |
| 3480 | const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs; |
| 3481 | if (Info.ExpandUnderForgetSubstitions) |
| 3482 | ArgsForSubst = &EmptyList; |
| 3483 | |
| 3484 | if (Info.Expand) { |
| 3485 | for (unsigned I = 0; I != *Info.NumExpansions; ++I) { |
| 3486 | Sema::ArgPackSubstIndexRAII SubstIndex(*this, I); |
| 3487 | |
| 3488 | TypeSourceInfo *Expanded = |
| 3489 | SubstType(T: BaseTypeLoc, Args: *ArgsForSubst, |
| 3490 | Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName()); |
| 3491 | if (!Expanded) { |
| 3492 | Invalid = true; |
| 3493 | continue; |
| 3494 | } |
| 3495 | |
| 3496 | if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier( |
| 3497 | Class: Instantiation, SpecifierRange: Base.getSourceRange(), Virtual: Base.isVirtual(), |
| 3498 | Access: Base.getAccessSpecifierAsWritten(), TInfo: Expanded, |
| 3499 | EllipsisLoc: SourceLocation())) |
| 3500 | InstantiatedBases.push_back(Elt: InstantiatedBase); |
| 3501 | else |
| 3502 | Invalid = true; |
| 3503 | } |
| 3504 | |
| 3505 | continue; |
| 3506 | } |
| 3507 | |
| 3508 | // The resulting base specifier will (still) be a pack expansion. |
| 3509 | EllipsisLoc = Base.getEllipsisLoc(); |
| 3510 | Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt); |
| 3511 | BaseTypeLoc = |
| 3512 | SubstType(T: BaseTypeLoc, Args: *ArgsForSubst, |
| 3513 | Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName()); |
| 3514 | } else { |
| 3515 | BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(), |
| 3516 | Args: TemplateArgs, |
| 3517 | Loc: Base.getSourceRange().getBegin(), |
| 3518 | Entity: DeclarationName()); |
| 3519 | } |
| 3520 | |
| 3521 | if (!BaseTypeLoc) { |
| 3522 | Invalid = true; |
| 3523 | continue; |
| 3524 | } |
| 3525 | |
| 3526 | if (CXXBaseSpecifier *InstantiatedBase |
| 3527 | = CheckBaseSpecifier(Class: Instantiation, |
| 3528 | SpecifierRange: Base.getSourceRange(), |
| 3529 | Virtual: Base.isVirtual(), |
| 3530 | Access: Base.getAccessSpecifierAsWritten(), |
| 3531 | TInfo: BaseTypeLoc, |
| 3532 | EllipsisLoc)) |
| 3533 | InstantiatedBases.push_back(Elt: InstantiatedBase); |
| 3534 | else |
| 3535 | Invalid = true; |
| 3536 | } |
| 3537 | |
| 3538 | if (!Invalid && AttachBaseSpecifiers(Class: Instantiation, Bases: InstantiatedBases)) |
| 3539 | Invalid = true; |
| 3540 | |
| 3541 | return Invalid; |
| 3542 | } |
| 3543 | |
| 3544 | // Defined via #include from SemaTemplateInstantiateDecl.cpp |
| 3545 | namespace clang { |
| 3546 | namespace sema { |
| 3547 | Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, |
| 3548 | const MultiLevelTemplateArgumentList &TemplateArgs); |
| 3549 | Attr *instantiateTemplateAttributeForDecl( |
| 3550 | const Attr *At, ASTContext &C, Sema &S, |
| 3551 | const MultiLevelTemplateArgumentList &TemplateArgs); |
| 3552 | } |
| 3553 | } |
| 3554 | |
| 3555 | bool Sema::InstantiateClass(SourceLocation PointOfInstantiation, |
| 3556 | CXXRecordDecl *Instantiation, |
| 3557 | CXXRecordDecl *Pattern, |
| 3558 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3559 | TemplateSpecializationKind TSK, bool Complain) { |
| 3560 | #ifndef NDEBUG |
| 3561 | RecursiveInstGuard AlreadyInstantiating(*this, Instantiation, |
| 3562 | RecursiveInstGuard::Kind::Template); |
| 3563 | assert(!AlreadyInstantiating && "should have been caught by caller" ); |
| 3564 | #endif |
| 3565 | |
| 3566 | return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern, |
| 3567 | TemplateArgs, TSK, Complain); |
| 3568 | } |
| 3569 | |
| 3570 | bool Sema::InstantiateClassImpl( |
| 3571 | SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, |
| 3572 | CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3573 | TemplateSpecializationKind TSK, bool Complain) { |
| 3574 | |
| 3575 | CXXRecordDecl *PatternDef |
| 3576 | = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition()); |
| 3577 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, |
| 3578 | InstantiatedFromMember: Instantiation->getInstantiatedFromMemberClass(), |
| 3579 | Pattern, PatternDef, TSK, Complain)) |
| 3580 | return true; |
| 3581 | |
| 3582 | llvm::TimeTraceScope TimeScope("InstantiateClass" , [&]() { |
| 3583 | llvm::TimeTraceMetadata M; |
| 3584 | llvm::raw_string_ostream OS(M.Detail); |
| 3585 | Instantiation->getNameForDiagnostic(OS, Policy: getPrintingPolicy(), |
| 3586 | /*Qualified=*/true); |
| 3587 | if (llvm::isTimeTraceVerbose()) { |
| 3588 | auto Loc = SourceMgr.getExpansionLoc(Loc: Instantiation->getLocation()); |
| 3589 | M.File = SourceMgr.getFilename(SpellingLoc: Loc); |
| 3590 | M.Line = SourceMgr.getExpansionLineNumber(Loc); |
| 3591 | } |
| 3592 | return M; |
| 3593 | }); |
| 3594 | |
| 3595 | Pattern = PatternDef; |
| 3596 | |
| 3597 | // Record the point of instantiation. |
| 3598 | if (MemberSpecializationInfo *MSInfo |
| 3599 | = Instantiation->getMemberSpecializationInfo()) { |
| 3600 | MSInfo->setTemplateSpecializationKind(TSK); |
| 3601 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 3602 | } else if (ClassTemplateSpecializationDecl *Spec |
| 3603 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: Instantiation)) { |
| 3604 | Spec->setTemplateSpecializationKind(TSK); |
| 3605 | Spec->setPointOfInstantiation(PointOfInstantiation); |
| 3606 | } |
| 3607 | |
| 3608 | NonSFINAEContext _(*this); |
| 3609 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
| 3610 | if (Inst.isInvalid()) |
| 3611 | return true; |
| 3612 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
| 3613 | "instantiating class definition" ); |
| 3614 | |
| 3615 | // Enter the scope of this instantiation. We don't use |
| 3616 | // PushDeclContext because we don't have a scope. |
| 3617 | ContextRAII SavedContext(*this, Instantiation); |
| 3618 | EnterExpressionEvaluationContext EvalContext( |
| 3619 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
| 3620 | |
| 3621 | // If this is an instantiation of a local class, merge this local |
| 3622 | // instantiation scope with the enclosing scope. Otherwise, every |
| 3623 | // instantiation of a class has its own local instantiation scope. |
| 3624 | bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); |
| 3625 | LocalInstantiationScope Scope(*this, MergeWithParentScope); |
| 3626 | |
| 3627 | // Some class state isn't processed immediately but delayed till class |
| 3628 | // instantiation completes. We may not be ready to handle any delayed state |
| 3629 | // already on the stack as it might correspond to a different class, so save |
| 3630 | // it now and put it back later. |
| 3631 | SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this); |
| 3632 | |
| 3633 | // Pull attributes from the pattern onto the instantiation. |
| 3634 | InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation); |
| 3635 | |
| 3636 | // Start the definition of this instantiation. |
| 3637 | Instantiation->startDefinition(); |
| 3638 | |
| 3639 | // The instantiation is visible here, even if it was first declared in an |
| 3640 | // unimported module. |
| 3641 | Instantiation->setVisibleDespiteOwningModule(); |
| 3642 | |
| 3643 | // FIXME: This loses the as-written tag kind for an explicit instantiation. |
| 3644 | Instantiation->setTagKind(Pattern->getTagKind()); |
| 3645 | |
| 3646 | // Do substitution on the base class specifiers. |
| 3647 | if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) |
| 3648 | Instantiation->setInvalidDecl(); |
| 3649 | |
| 3650 | TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); |
| 3651 | Instantiator.setEvaluateConstraints(false); |
| 3652 | SmallVector<Decl*, 4> Fields; |
| 3653 | // Delay instantiation of late parsed attributes. |
| 3654 | LateInstantiatedAttrVec LateAttrs; |
| 3655 | Instantiator.enableLateAttributeInstantiation(LA: &LateAttrs); |
| 3656 | |
| 3657 | bool MightHaveConstexprVirtualFunctions = false; |
| 3658 | for (auto *Member : Pattern->decls()) { |
| 3659 | // Don't instantiate members not belonging in this semantic context. |
| 3660 | // e.g. for: |
| 3661 | // @code |
| 3662 | // template <int i> class A { |
| 3663 | // class B *g; |
| 3664 | // }; |
| 3665 | // @endcode |
| 3666 | // 'class B' has the template as lexical context but semantically it is |
| 3667 | // introduced in namespace scope. |
| 3668 | if (Member->getDeclContext() != Pattern) |
| 3669 | continue; |
| 3670 | |
| 3671 | // BlockDecls can appear in a default-member-initializer. They must be the |
| 3672 | // child of a BlockExpr, so we only know how to instantiate them from there. |
| 3673 | // Similarly, lambda closure types are recreated when instantiating the |
| 3674 | // corresponding LambdaExpr. |
| 3675 | if (isa<BlockDecl>(Val: Member) || |
| 3676 | (isa<CXXRecordDecl>(Val: Member) && cast<CXXRecordDecl>(Val: Member)->isLambda())) |
| 3677 | continue; |
| 3678 | |
| 3679 | if (Member->isInvalidDecl()) { |
| 3680 | Instantiation->setInvalidDecl(); |
| 3681 | // Drop invalid members to prevent cascading diagnostic errors. |
| 3682 | // We make an exception for VarTemplateDecl because the primary template |
| 3683 | // is required for partial specialization lookup. Keeping it is safe from |
| 3684 | // cascading errors due to the parser's type recovery. |
| 3685 | if (!isa<VarTemplateDecl>(Val: Member)) |
| 3686 | continue; |
| 3687 | } |
| 3688 | |
| 3689 | Decl *NewMember = Instantiator.Visit(D: Member); |
| 3690 | if (NewMember) { |
| 3691 | if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: NewMember)) { |
| 3692 | Fields.push_back(Elt: Field); |
| 3693 | } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Val: NewMember)) { |
| 3694 | // C++11 [temp.inst]p1: The implicit instantiation of a class template |
| 3695 | // specialization causes the implicit instantiation of the definitions |
| 3696 | // of unscoped member enumerations. |
| 3697 | // Record a point of instantiation for this implicit instantiation. |
| 3698 | if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && |
| 3699 | Enum->isCompleteDefinition()) { |
| 3700 | MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); |
| 3701 | assert(MSInfo && "no spec info for member enum specialization" ); |
| 3702 | MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); |
| 3703 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 3704 | } |
| 3705 | } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(Val: NewMember)) { |
| 3706 | if (SA->isFailed()) { |
| 3707 | // A static_assert failed. Bail out; instantiating this |
| 3708 | // class is probably not meaningful. |
| 3709 | Instantiation->setInvalidDecl(); |
| 3710 | break; |
| 3711 | } |
| 3712 | } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewMember)) { |
| 3713 | if (MD->isConstexpr() && !MD->getFriendObjectKind() && |
| 3714 | (MD->isVirtualAsWritten() || Instantiation->getNumBases())) |
| 3715 | MightHaveConstexprVirtualFunctions = true; |
| 3716 | } |
| 3717 | |
| 3718 | if (Member->isInvalidDecl()) |
| 3719 | NewMember->setInvalidDecl(); |
| 3720 | |
| 3721 | if (NewMember->isInvalidDecl()) |
| 3722 | Instantiation->setInvalidDecl(); |
| 3723 | } else { |
| 3724 | // FIXME: Eventually, a NULL return will mean that one of the |
| 3725 | // instantiations was a semantic disaster, and we'll want to mark the |
| 3726 | // declaration invalid. |
| 3727 | // For now, we expect to skip some members that we can't yet handle. |
| 3728 | } |
| 3729 | } |
| 3730 | |
| 3731 | // Finish checking fields. |
| 3732 | ActOnFields(S: nullptr, RecLoc: Instantiation->getLocation(), TagDecl: Instantiation, Fields, |
| 3733 | LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView()); |
| 3734 | CheckCompletedCXXClass(S: nullptr, Record: Instantiation); |
| 3735 | |
| 3736 | // Default arguments are parsed, if not instantiated. We can go instantiate |
| 3737 | // default arg exprs for default constructors if necessary now. Unless we're |
| 3738 | // parsing a class, in which case wait until that's finished. |
| 3739 | if (ParsingClassDepth == 0) |
| 3740 | ActOnFinishCXXNonNestedClass(); |
| 3741 | |
| 3742 | // Instantiate late parsed attributes, and attach them to their decls. |
| 3743 | // See Sema::InstantiateAttrs |
| 3744 | for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(), |
| 3745 | E = LateAttrs.end(); I != E; ++I) { |
| 3746 | assert(CurrentInstantiationScope == Instantiator.getStartingScope()); |
| 3747 | CurrentInstantiationScope = I->Scope; |
| 3748 | |
| 3749 | // Allow 'this' within late-parsed attributes. |
| 3750 | auto *ND = cast<NamedDecl>(Val: I->NewDecl); |
| 3751 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext()); |
| 3752 | CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), |
| 3753 | ND->isCXXInstanceMember()); |
| 3754 | |
| 3755 | Attr *NewAttr = |
| 3756 | instantiateTemplateAttribute(At: I->TmplAttr, C&: Context, S&: *this, TemplateArgs); |
| 3757 | if (NewAttr && checkInstantiatedThreadSafetyAttrs(D: I->NewDecl, A: NewAttr)) |
| 3758 | I->NewDecl->addAttr(A: NewAttr); |
| 3759 | LocalInstantiationScope::deleteScopes(Scope: I->Scope, |
| 3760 | Outermost: Instantiator.getStartingScope()); |
| 3761 | } |
| 3762 | Instantiator.disableLateAttributeInstantiation(); |
| 3763 | LateAttrs.clear(); |
| 3764 | |
| 3765 | ActOnFinishDelayedMemberInitializers(Record: Instantiation); |
| 3766 | |
| 3767 | // FIXME: We should do something similar for explicit instantiations so they |
| 3768 | // end up in the right module. |
| 3769 | if (TSK == TSK_ImplicitInstantiation) { |
| 3770 | Instantiation->setLocation(Pattern->getLocation()); |
| 3771 | Instantiation->setLocStart(Pattern->getInnerLocStart()); |
| 3772 | Instantiation->setBraceRange(Pattern->getBraceRange()); |
| 3773 | } |
| 3774 | |
| 3775 | if (!Instantiation->isInvalidDecl()) { |
| 3776 | // Perform any dependent diagnostics from the pattern. |
| 3777 | if (Pattern->isDependentContext()) |
| 3778 | PerformDependentDiagnostics(Pattern, TemplateArgs); |
| 3779 | |
| 3780 | // Instantiate any out-of-line class template partial |
| 3781 | // specializations now. |
| 3782 | for (TemplateDeclInstantiator::delayed_partial_spec_iterator |
| 3783 | P = Instantiator.delayed_partial_spec_begin(), |
| 3784 | PEnd = Instantiator.delayed_partial_spec_end(); |
| 3785 | P != PEnd; ++P) { |
| 3786 | if (!Instantiator.InstantiateClassTemplatePartialSpecialization( |
| 3787 | ClassTemplate: P->first, PartialSpec: P->second)) { |
| 3788 | Instantiation->setInvalidDecl(); |
| 3789 | break; |
| 3790 | } |
| 3791 | } |
| 3792 | |
| 3793 | // Instantiate any out-of-line variable template partial |
| 3794 | // specializations now. |
| 3795 | for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator |
| 3796 | P = Instantiator.delayed_var_partial_spec_begin(), |
| 3797 | PEnd = Instantiator.delayed_var_partial_spec_end(); |
| 3798 | P != PEnd; ++P) { |
| 3799 | if (!Instantiator.InstantiateVarTemplatePartialSpecialization( |
| 3800 | VarTemplate: P->first, PartialSpec: P->second)) { |
| 3801 | Instantiation->setInvalidDecl(); |
| 3802 | break; |
| 3803 | } |
| 3804 | } |
| 3805 | } |
| 3806 | |
| 3807 | Instantiation->setIsHLSLBuiltinRecord(Pattern->isHLSLBuiltinRecord()); |
| 3808 | |
| 3809 | // Exit the scope of this instantiation. |
| 3810 | SavedContext.pop(); |
| 3811 | |
| 3812 | if (!Instantiation->isInvalidDecl()) { |
| 3813 | // Always emit the vtable for an explicit instantiation definition |
| 3814 | // of a polymorphic class template specialization. Otherwise, eagerly |
| 3815 | // instantiate only constexpr virtual functions in preparation for their use |
| 3816 | // in constant evaluation. |
| 3817 | if (TSK == TSK_ExplicitInstantiationDefinition) |
| 3818 | MarkVTableUsed(Loc: PointOfInstantiation, Class: Instantiation, DefinitionRequired: true); |
| 3819 | else if (MightHaveConstexprVirtualFunctions) |
| 3820 | MarkVirtualMembersReferenced(Loc: PointOfInstantiation, RD: Instantiation, |
| 3821 | /*ConstexprOnly*/ true); |
| 3822 | } |
| 3823 | |
| 3824 | Consumer.HandleTagDeclDefinition(D: Instantiation); |
| 3825 | |
| 3826 | return Instantiation->isInvalidDecl(); |
| 3827 | } |
| 3828 | |
| 3829 | bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, |
| 3830 | EnumDecl *Instantiation, EnumDecl *Pattern, |
| 3831 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3832 | TemplateSpecializationKind TSK) { |
| 3833 | #ifndef NDEBUG |
| 3834 | RecursiveInstGuard AlreadyInstantiating(*this, Instantiation, |
| 3835 | RecursiveInstGuard::Kind::Template); |
| 3836 | assert(!AlreadyInstantiating && "should have been caught by caller" ); |
| 3837 | #endif |
| 3838 | |
| 3839 | EnumDecl *PatternDef = Pattern->getDefinition(); |
| 3840 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, |
| 3841 | InstantiatedFromMember: Instantiation->getInstantiatedFromMemberEnum(), |
| 3842 | Pattern, PatternDef, TSK,/*Complain*/true)) |
| 3843 | return true; |
| 3844 | Pattern = PatternDef; |
| 3845 | |
| 3846 | // Record the point of instantiation. |
| 3847 | if (MemberSpecializationInfo *MSInfo |
| 3848 | = Instantiation->getMemberSpecializationInfo()) { |
| 3849 | MSInfo->setTemplateSpecializationKind(TSK); |
| 3850 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 3851 | } |
| 3852 | |
| 3853 | NonSFINAEContext _(*this); |
| 3854 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
| 3855 | if (Inst.isInvalid()) |
| 3856 | return true; |
| 3857 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
| 3858 | "instantiating enum definition" ); |
| 3859 | |
| 3860 | // The instantiation is visible here, even if it was first declared in an |
| 3861 | // unimported module. |
| 3862 | Instantiation->setVisibleDespiteOwningModule(); |
| 3863 | |
| 3864 | // Enter the scope of this instantiation. We don't use |
| 3865 | // PushDeclContext because we don't have a scope. |
| 3866 | ContextRAII SavedContext(*this, Instantiation); |
| 3867 | EnterExpressionEvaluationContext EvalContext( |
| 3868 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
| 3869 | |
| 3870 | LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); |
| 3871 | |
| 3872 | // Pull attributes from the pattern onto the instantiation. |
| 3873 | InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation); |
| 3874 | |
| 3875 | TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); |
| 3876 | Instantiator.InstantiateEnumDefinition(Enum: Instantiation, Pattern); |
| 3877 | |
| 3878 | // Exit the scope of this instantiation. |
| 3879 | SavedContext.pop(); |
| 3880 | |
| 3881 | return Instantiation->isInvalidDecl(); |
| 3882 | } |
| 3883 | |
| 3884 | bool Sema::InstantiateInClassInitializer( |
| 3885 | SourceLocation PointOfInstantiation, FieldDecl *Instantiation, |
| 3886 | FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 3887 | // If there is no initializer, we don't need to do anything. |
| 3888 | if (!Pattern->hasInClassInitializer()) |
| 3889 | return false; |
| 3890 | |
| 3891 | assert(Instantiation->getInClassInitStyle() == |
| 3892 | Pattern->getInClassInitStyle() && |
| 3893 | "pattern and instantiation disagree about init style" ); |
| 3894 | |
| 3895 | RecursiveInstGuard AlreadyInstantiating(*this, Instantiation, |
| 3896 | RecursiveInstGuard::Kind::Template); |
| 3897 | if (AlreadyInstantiating) |
| 3898 | // Error out if we hit an instantiation cycle for this initializer. |
| 3899 | return Diag(Loc: PointOfInstantiation, |
| 3900 | DiagID: diag::err_default_member_initializer_cycle) |
| 3901 | << Instantiation; |
| 3902 | |
| 3903 | // Error out if we haven't parsed the initializer of the pattern yet because |
| 3904 | // we are waiting for the closing brace of the outer class. |
| 3905 | Expr *OldInit = Pattern->getInClassInitializer(); |
| 3906 | if (!OldInit) { |
| 3907 | RecordDecl *PatternRD = Pattern->getParent(); |
| 3908 | RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext(); |
| 3909 | Diag(Loc: PointOfInstantiation, |
| 3910 | DiagID: diag::err_default_member_initializer_not_yet_parsed) |
| 3911 | << OutermostClass << Pattern; |
| 3912 | Diag(Loc: Pattern->getEndLoc(), |
| 3913 | DiagID: diag::note_default_member_initializer_not_yet_parsed); |
| 3914 | Instantiation->setInvalidDecl(); |
| 3915 | return true; |
| 3916 | } |
| 3917 | |
| 3918 | NonSFINAEContext _(*this); |
| 3919 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
| 3920 | if (Inst.isInvalid()) |
| 3921 | return true; |
| 3922 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
| 3923 | "instantiating default member init" ); |
| 3924 | |
| 3925 | // Enter the scope of this instantiation. We don't use PushDeclContext because |
| 3926 | // we don't have a scope. |
| 3927 | ContextRAII SavedContext(*this, Instantiation->getParent()); |
| 3928 | EnterExpressionEvaluationContext EvalContext( |
| 3929 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, |
| 3930 | Instantiation); |
| 3931 | ExprEvalContexts.back().DelayedDefaultInitializationContext = { |
| 3932 | PointOfInstantiation, Instantiation, CurContext}; |
| 3933 | |
| 3934 | LocalInstantiationScope Scope(*this, true); |
| 3935 | |
| 3936 | // Instantiate the initializer. |
| 3937 | ActOnStartCXXInClassMemberInitializer(); |
| 3938 | CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers()); |
| 3939 | |
| 3940 | ExprResult NewInit = SubstInitializer(E: OldInit, TemplateArgs, |
| 3941 | /*CXXDirectInit=*/false); |
| 3942 | Expr *Init = NewInit.get(); |
| 3943 | assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class" ); |
| 3944 | ActOnFinishCXXInClassMemberInitializer( |
| 3945 | VarDecl: Instantiation, EqualLoc: Init ? Init->getBeginLoc() : SourceLocation(), Init); |
| 3946 | |
| 3947 | if (auto *L = getASTMutationListener()) |
| 3948 | L->DefaultMemberInitializerInstantiated(D: Instantiation); |
| 3949 | |
| 3950 | // Return true if the in-class initializer is still missing. |
| 3951 | return !Instantiation->getInClassInitializer(); |
| 3952 | } |
| 3953 | |
| 3954 | namespace { |
| 3955 | /// A partial specialization whose template arguments have matched |
| 3956 | /// a given template-id. |
| 3957 | struct PartialSpecMatchResult { |
| 3958 | ClassTemplatePartialSpecializationDecl *Partial; |
| 3959 | TemplateArgumentList *Args; |
| 3960 | }; |
| 3961 | } |
| 3962 | |
| 3963 | bool Sema::usesPartialOrExplicitSpecialization( |
| 3964 | SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) { |
| 3965 | if (ClassTemplateSpec->getTemplateSpecializationKind() == |
| 3966 | TSK_ExplicitSpecialization) |
| 3967 | return true; |
| 3968 | |
| 3969 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
| 3970 | ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate(); |
| 3971 | CTD->getPartialSpecializations(PS&: PartialSpecs); |
| 3972 | for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) { |
| 3973 | // C++ [temp.spec.partial.member]p2: |
| 3974 | // If the primary member template is explicitly specialized for a given |
| 3975 | // (implicit) specialization of the enclosing class template, the partial |
| 3976 | // specializations of the member template are ignored for this |
| 3977 | // specialization of the enclosing class template. If a partial |
| 3978 | // specialization of the member template is explicitly specialized for a |
| 3979 | // given (implicit) specialization of the enclosing class template, the |
| 3980 | // primary member template and its other partial specializations are still |
| 3981 | // considered for this specialization of the enclosing class template. |
| 3982 | if (CTD->isMemberSpecialization() && !CTPSD->isMemberSpecialization()) |
| 3983 | continue; |
| 3984 | |
| 3985 | TemplateDeductionInfo Info(Loc); |
| 3986 | if (DeduceTemplateArguments(Partial: CTPSD, |
| 3987 | TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), |
| 3988 | Info) == TemplateDeductionResult::Success) |
| 3989 | return true; |
| 3990 | } |
| 3991 | |
| 3992 | return false; |
| 3993 | } |
| 3994 | |
| 3995 | /// Get the instantiation pattern to use to instantiate the definition of a |
| 3996 | /// given ClassTemplateSpecializationDecl (either the pattern of the primary |
| 3997 | /// template or of a partial specialization). |
| 3998 | static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization( |
| 3999 | Sema &S, SourceLocation PointOfInstantiation, |
| 4000 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
| 4001 | TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) { |
| 4002 | std::optional<Sema::NonSFINAEContext> NSC(S); |
| 4003 | Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec); |
| 4004 | if (Inst.isInvalid()) |
| 4005 | return {/*Invalid=*/true}; |
| 4006 | |
| 4007 | llvm::PointerUnion<ClassTemplateDecl *, |
| 4008 | ClassTemplatePartialSpecializationDecl *> |
| 4009 | Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); |
| 4010 | if (!isa<ClassTemplatePartialSpecializationDecl *>(Val: Specialized)) { |
| 4011 | // Find best matching specialization. |
| 4012 | ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); |
| 4013 | |
| 4014 | // C++ [temp.class.spec.match]p1: |
| 4015 | // When a class template is used in a context that requires an |
| 4016 | // instantiation of the class, it is necessary to determine |
| 4017 | // whether the instantiation is to be generated using the primary |
| 4018 | // template or one of the partial specializations. This is done by |
| 4019 | // matching the template arguments of the class template |
| 4020 | // specialization with the template argument lists of the partial |
| 4021 | // specializations. |
| 4022 | typedef PartialSpecMatchResult MatchResult; |
| 4023 | SmallVector<MatchResult, 4> Matched, ; |
| 4024 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
| 4025 | Template->getPartialSpecializations(PS&: PartialSpecs); |
| 4026 | TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); |
| 4027 | for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) { |
| 4028 | // C++ [temp.spec.partial.member]p2: |
| 4029 | // If the primary member template is explicitly specialized for a given |
| 4030 | // (implicit) specialization of the enclosing class template, the |
| 4031 | // partial specializations of the member template are ignored for this |
| 4032 | // specialization of the enclosing class template. If a partial |
| 4033 | // specialization of the member template is explicitly specialized for a |
| 4034 | // given (implicit) specialization of the enclosing class template, the |
| 4035 | // primary member template and its other partial specializations are |
| 4036 | // still considered for this specialization of the enclosing class |
| 4037 | // template. |
| 4038 | if (Template->isMemberSpecialization() && |
| 4039 | !Partial->isMemberSpecialization()) |
| 4040 | continue; |
| 4041 | |
| 4042 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
| 4043 | if (TemplateDeductionResult Result = S.DeduceTemplateArguments( |
| 4044 | Partial, TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), Info); |
| 4045 | Result != TemplateDeductionResult::Success) { |
| 4046 | // Store the failed-deduction information for use in diagnostics, later. |
| 4047 | // TODO: Actually use the failed-deduction info? |
| 4048 | FailedCandidates.addCandidate().set( |
| 4049 | Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial, |
| 4050 | Info: MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info)); |
| 4051 | (void)Result; |
| 4052 | } else { |
| 4053 | auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched; |
| 4054 | List.push_back(Elt: MatchResult{.Partial: Partial, .Args: Info.takeCanonical()}); |
| 4055 | } |
| 4056 | } |
| 4057 | if (Matched.empty() && PrimaryStrictPackMatch) |
| 4058 | Matched = std::move(ExtraMatched); |
| 4059 | |
| 4060 | // If we're dealing with a member template where the template parameters |
| 4061 | // have been instantiated, this provides the original template parameters |
| 4062 | // from which the member template's parameters were instantiated. |
| 4063 | |
| 4064 | if (Matched.size() >= 1) { |
| 4065 | SmallVectorImpl<MatchResult>::iterator Best = Matched.begin(); |
| 4066 | if (Matched.size() == 1) { |
| 4067 | // -- If exactly one matching specialization is found, the |
| 4068 | // instantiation is generated from that specialization. |
| 4069 | // We don't need to do anything for this. |
| 4070 | } else { |
| 4071 | // -- If more than one matching specialization is found, the |
| 4072 | // partial order rules (14.5.4.2) are used to determine |
| 4073 | // whether one of the specializations is more specialized |
| 4074 | // than the others. If none of the specializations is more |
| 4075 | // specialized than all of the other matching |
| 4076 | // specializations, then the use of the class template is |
| 4077 | // ambiguous and the program is ill-formed. |
| 4078 | for (SmallVectorImpl<MatchResult>::iterator P = Best + 1, |
| 4079 | PEnd = Matched.end(); |
| 4080 | P != PEnd; ++P) { |
| 4081 | if (S.getMoreSpecializedPartialSpecialization( |
| 4082 | PS1: P->Partial, PS2: Best->Partial, Loc: PointOfInstantiation) == |
| 4083 | P->Partial) |
| 4084 | Best = P; |
| 4085 | } |
| 4086 | |
| 4087 | // Determine if the best partial specialization is more specialized than |
| 4088 | // the others. |
| 4089 | bool Ambiguous = false; |
| 4090 | for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), |
| 4091 | PEnd = Matched.end(); |
| 4092 | P != PEnd; ++P) { |
| 4093 | if (P != Best && S.getMoreSpecializedPartialSpecialization( |
| 4094 | PS1: P->Partial, PS2: Best->Partial, |
| 4095 | Loc: PointOfInstantiation) != Best->Partial) { |
| 4096 | Ambiguous = true; |
| 4097 | break; |
| 4098 | } |
| 4099 | } |
| 4100 | |
| 4101 | if (Ambiguous) { |
| 4102 | // Partial ordering did not produce a clear winner. Complain. |
| 4103 | Inst.Clear(); |
| 4104 | NSC.reset(); |
| 4105 | S.Diag(Loc: PointOfInstantiation, |
| 4106 | DiagID: diag::err_partial_spec_ordering_ambiguous) |
| 4107 | << ClassTemplateSpec; |
| 4108 | |
| 4109 | // Print the matching partial specializations. |
| 4110 | for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), |
| 4111 | PEnd = Matched.end(); |
| 4112 | P != PEnd; ++P) |
| 4113 | S.Diag(Loc: P->Partial->getLocation(), DiagID: diag::note_partial_spec_match) |
| 4114 | << S.getTemplateArgumentBindingsText( |
| 4115 | Params: P->Partial->getTemplateParameters(), Args: *P->Args); |
| 4116 | |
| 4117 | return {/*Invalid=*/true}; |
| 4118 | } |
| 4119 | } |
| 4120 | |
| 4121 | ClassTemplateSpec->setInstantiationOf(PartialSpec: Best->Partial, TemplateArgs: Best->Args); |
| 4122 | } else { |
| 4123 | // -- If no matches are found, the instantiation is generated |
| 4124 | // from the primary template. |
| 4125 | } |
| 4126 | } |
| 4127 | |
| 4128 | CXXRecordDecl *Pattern = nullptr; |
| 4129 | Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); |
| 4130 | if (auto *PartialSpec = |
| 4131 | Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { |
| 4132 | // Instantiate using the best class template partial specialization. |
| 4133 | while (PartialSpec->getInstantiatedFromMember()) { |
| 4134 | // If we've found an explicit specialization of this class template, |
| 4135 | // stop here and use that as the pattern. |
| 4136 | if (PartialSpec->isMemberSpecialization()) |
| 4137 | break; |
| 4138 | |
| 4139 | PartialSpec = PartialSpec->getInstantiatedFromMember(); |
| 4140 | } |
| 4141 | Pattern = PartialSpec; |
| 4142 | } else { |
| 4143 | ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); |
| 4144 | while (Template->getInstantiatedFromMemberTemplate()) { |
| 4145 | // If we've found an explicit specialization of this class template, |
| 4146 | // stop here and use that as the pattern. |
| 4147 | if (Template->isMemberSpecialization()) |
| 4148 | break; |
| 4149 | |
| 4150 | Template = Template->getInstantiatedFromMemberTemplate(); |
| 4151 | } |
| 4152 | Pattern = Template->getTemplatedDecl(); |
| 4153 | } |
| 4154 | |
| 4155 | return Pattern; |
| 4156 | } |
| 4157 | |
| 4158 | bool Sema::InstantiateClassTemplateSpecialization( |
| 4159 | SourceLocation PointOfInstantiation, |
| 4160 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
| 4161 | TemplateSpecializationKind TSK, bool Complain, |
| 4162 | bool PrimaryStrictPackMatch) { |
| 4163 | // Perform the actual instantiation on the canonical declaration. |
| 4164 | ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( |
| 4165 | Val: ClassTemplateSpec->getCanonicalDecl()); |
| 4166 | if (ClassTemplateSpec->isInvalidDecl()) |
| 4167 | return true; |
| 4168 | |
| 4169 | Sema::RecursiveInstGuard AlreadyInstantiating( |
| 4170 | *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template); |
| 4171 | if (AlreadyInstantiating) |
| 4172 | return false; |
| 4173 | |
| 4174 | bool HadAvaibilityWarning = |
| 4175 | ShouldDiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Message: nullptr, ClassReceiver: nullptr) |
| 4176 | .first != AR_Available; |
| 4177 | |
| 4178 | ActionResult<CXXRecordDecl *> Pattern = |
| 4179 | getPatternForClassTemplateSpecialization(S&: *this, PointOfInstantiation, |
| 4180 | ClassTemplateSpec, TSK, |
| 4181 | PrimaryStrictPackMatch); |
| 4182 | |
| 4183 | if (!Pattern.isUsable()) |
| 4184 | return Pattern.isInvalid(); |
| 4185 | |
| 4186 | bool Err = InstantiateClassImpl( |
| 4187 | PointOfInstantiation, Instantiation: ClassTemplateSpec, Pattern: Pattern.get(), |
| 4188 | TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec), TSK, Complain); |
| 4189 | |
| 4190 | // If we haven't already warn on avaibility, consider the avaibility |
| 4191 | // attributes of the partial specialization. |
| 4192 | // Note that - because we need to have deduced the partial specialization - |
| 4193 | // We can only emit these warnings when the specialization is instantiated. |
| 4194 | if (!Err && !HadAvaibilityWarning) { |
| 4195 | assert(ClassTemplateSpec->getTemplateSpecializationKind() != |
| 4196 | TSK_Undeclared); |
| 4197 | DiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Locs: PointOfInstantiation); |
| 4198 | } |
| 4199 | return Err; |
| 4200 | } |
| 4201 | |
| 4202 | void |
| 4203 | Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, |
| 4204 | CXXRecordDecl *Instantiation, |
| 4205 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4206 | TemplateSpecializationKind TSK) { |
| 4207 | // FIXME: We need to notify the ASTMutationListener that we did all of these |
| 4208 | // things, in case we have an explicit instantiation definition in a PCM, a |
| 4209 | // module, or preamble, and the declaration is in an imported AST. |
| 4210 | assert( |
| 4211 | (TSK == TSK_ExplicitInstantiationDefinition || |
| 4212 | TSK == TSK_ExplicitInstantiationDeclaration || |
| 4213 | (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && |
| 4214 | "Unexpected template specialization kind!" ); |
| 4215 | for (auto *D : Instantiation->decls()) { |
| 4216 | bool SuppressNew = false; |
| 4217 | if (auto *Function = dyn_cast<FunctionDecl>(Val: D)) { |
| 4218 | if (FunctionDecl *Pattern = |
| 4219 | Function->getInstantiatedFromMemberFunction()) { |
| 4220 | |
| 4221 | if (Function->getTrailingRequiresClause()) { |
| 4222 | ConstraintSatisfaction Satisfaction; |
| 4223 | if (CheckFunctionConstraints(FD: Function, Satisfaction) || |
| 4224 | !Satisfaction.IsSatisfied) { |
| 4225 | continue; |
| 4226 | } |
| 4227 | } |
| 4228 | |
| 4229 | if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 4230 | continue; |
| 4231 | |
| 4232 | TemplateSpecializationKind PrevTSK = |
| 4233 | Function->getTemplateSpecializationKind(); |
| 4234 | if (PrevTSK == TSK_ExplicitSpecialization) |
| 4235 | continue; |
| 4236 | |
| 4237 | if (CheckSpecializationInstantiationRedecl( |
| 4238 | NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Function, PrevTSK, |
| 4239 | PrevPtOfInstantiation: Function->getPointOfInstantiation(), SuppressNew) || |
| 4240 | SuppressNew) |
| 4241 | continue; |
| 4242 | |
| 4243 | // C++11 [temp.explicit]p8: |
| 4244 | // An explicit instantiation definition that names a class template |
| 4245 | // specialization explicitly instantiates the class template |
| 4246 | // specialization and is only an explicit instantiation definition |
| 4247 | // of members whose definition is visible at the point of |
| 4248 | // instantiation. |
| 4249 | if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined()) |
| 4250 | continue; |
| 4251 | |
| 4252 | Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 4253 | |
| 4254 | if (Function->isDefined()) { |
| 4255 | // Let the ASTConsumer know that this function has been explicitly |
| 4256 | // instantiated now, and its linkage might have changed. |
| 4257 | Consumer.HandleTopLevelDecl(D: DeclGroupRef(Function)); |
| 4258 | } else if (TSK == TSK_ExplicitInstantiationDefinition) { |
| 4259 | InstantiateFunctionDefinition(PointOfInstantiation, Function); |
| 4260 | } else if (TSK == TSK_ImplicitInstantiation) { |
| 4261 | PendingLocalImplicitInstantiations.push_back( |
| 4262 | x: std::make_pair(x&: Function, y&: PointOfInstantiation)); |
| 4263 | } |
| 4264 | } |
| 4265 | } else if (auto *Var = dyn_cast<VarDecl>(Val: D)) { |
| 4266 | if (isa<VarTemplateSpecializationDecl>(Val: Var)) |
| 4267 | continue; |
| 4268 | |
| 4269 | if (Var->isStaticDataMember()) { |
| 4270 | if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 4271 | continue; |
| 4272 | |
| 4273 | MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); |
| 4274 | assert(MSInfo && "No member specialization information?" ); |
| 4275 | if (MSInfo->getTemplateSpecializationKind() |
| 4276 | == TSK_ExplicitSpecialization) |
| 4277 | continue; |
| 4278 | |
| 4279 | if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, |
| 4280 | PrevDecl: Var, |
| 4281 | PrevTSK: MSInfo->getTemplateSpecializationKind(), |
| 4282 | PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), |
| 4283 | SuppressNew) || |
| 4284 | SuppressNew) |
| 4285 | continue; |
| 4286 | |
| 4287 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
| 4288 | // C++0x [temp.explicit]p8: |
| 4289 | // An explicit instantiation definition that names a class template |
| 4290 | // specialization explicitly instantiates the class template |
| 4291 | // specialization and is only an explicit instantiation definition |
| 4292 | // of members whose definition is visible at the point of |
| 4293 | // instantiation. |
| 4294 | if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) |
| 4295 | continue; |
| 4296 | |
| 4297 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 4298 | InstantiateVariableDefinition(PointOfInstantiation, Var); |
| 4299 | } else { |
| 4300 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 4301 | } |
| 4302 | } |
| 4303 | } else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
| 4304 | if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 4305 | continue; |
| 4306 | |
| 4307 | // Always skip the injected-class-name, along with any |
| 4308 | // redeclarations of nested classes, since both would cause us |
| 4309 | // to try to instantiate the members of a class twice. |
| 4310 | // Skip closure types; they'll get instantiated when we instantiate |
| 4311 | // the corresponding lambda-expression. |
| 4312 | if (Record->isInjectedClassName() || Record->getPreviousDecl() || |
| 4313 | Record->isLambda()) |
| 4314 | continue; |
| 4315 | |
| 4316 | MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); |
| 4317 | assert(MSInfo && "No member specialization information?" ); |
| 4318 | |
| 4319 | if (MSInfo->getTemplateSpecializationKind() |
| 4320 | == TSK_ExplicitSpecialization) |
| 4321 | continue; |
| 4322 | |
| 4323 | if (Context.getTargetInfo().getTriple().isOSWindows() && |
| 4324 | TSK == TSK_ExplicitInstantiationDeclaration) { |
| 4325 | // On Windows, explicit instantiation decl of the outer class doesn't |
| 4326 | // affect the inner class. Typically extern template declarations are |
| 4327 | // used in combination with dll import/export annotations, but those |
| 4328 | // are not propagated from the outer class templates to inner classes. |
| 4329 | // Therefore, do not instantiate inner classes on this platform, so |
| 4330 | // that users don't end up with undefined symbols during linking. |
| 4331 | continue; |
| 4332 | } |
| 4333 | |
| 4334 | if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, |
| 4335 | PrevDecl: Record, |
| 4336 | PrevTSK: MSInfo->getTemplateSpecializationKind(), |
| 4337 | PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), |
| 4338 | SuppressNew) || |
| 4339 | SuppressNew) |
| 4340 | continue; |
| 4341 | |
| 4342 | CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); |
| 4343 | assert(Pattern && "Missing instantiated-from-template information" ); |
| 4344 | |
| 4345 | if (!Record->getDefinition()) { |
| 4346 | if (!Pattern->getDefinition()) { |
| 4347 | // C++0x [temp.explicit]p8: |
| 4348 | // An explicit instantiation definition that names a class template |
| 4349 | // specialization explicitly instantiates the class template |
| 4350 | // specialization and is only an explicit instantiation definition |
| 4351 | // of members whose definition is visible at the point of |
| 4352 | // instantiation. |
| 4353 | if (TSK == TSK_ExplicitInstantiationDeclaration) { |
| 4354 | MSInfo->setTemplateSpecializationKind(TSK); |
| 4355 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 4356 | } |
| 4357 | |
| 4358 | continue; |
| 4359 | } |
| 4360 | |
| 4361 | InstantiateClass(PointOfInstantiation, Instantiation: Record, Pattern, |
| 4362 | TemplateArgs, |
| 4363 | TSK); |
| 4364 | } else { |
| 4365 | if (TSK == TSK_ExplicitInstantiationDefinition && |
| 4366 | Record->getTemplateSpecializationKind() == |
| 4367 | TSK_ExplicitInstantiationDeclaration) { |
| 4368 | Record->setTemplateSpecializationKind(TSK); |
| 4369 | MarkVTableUsed(Loc: PointOfInstantiation, Class: Record, DefinitionRequired: true); |
| 4370 | } |
| 4371 | } |
| 4372 | |
| 4373 | Pattern = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition()); |
| 4374 | if (Pattern) |
| 4375 | InstantiateClassMembers(PointOfInstantiation, Instantiation: Pattern, TemplateArgs, |
| 4376 | TSK); |
| 4377 | } else if (auto *Enum = dyn_cast<EnumDecl>(Val: D)) { |
| 4378 | MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); |
| 4379 | assert(MSInfo && "No member specialization information?" ); |
| 4380 | |
| 4381 | if (MSInfo->getTemplateSpecializationKind() |
| 4382 | == TSK_ExplicitSpecialization) |
| 4383 | continue; |
| 4384 | |
| 4385 | if (CheckSpecializationInstantiationRedecl( |
| 4386 | NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Enum, |
| 4387 | PrevTSK: MSInfo->getTemplateSpecializationKind(), |
| 4388 | PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), SuppressNew) || |
| 4389 | SuppressNew) |
| 4390 | continue; |
| 4391 | |
| 4392 | if (Enum->getDefinition()) |
| 4393 | continue; |
| 4394 | |
| 4395 | EnumDecl *Pattern = Enum->getTemplateInstantiationPattern(); |
| 4396 | assert(Pattern && "Missing instantiated-from-template information" ); |
| 4397 | |
| 4398 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
| 4399 | if (!Pattern->getDefinition()) |
| 4400 | continue; |
| 4401 | |
| 4402 | InstantiateEnum(PointOfInstantiation, Instantiation: Enum, Pattern, TemplateArgs, TSK); |
| 4403 | } else { |
| 4404 | MSInfo->setTemplateSpecializationKind(TSK); |
| 4405 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 4406 | } |
| 4407 | } else if (auto *Field = dyn_cast<FieldDecl>(Val: D)) { |
| 4408 | // No need to instantiate in-class initializers during explicit |
| 4409 | // instantiation. |
| 4410 | if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) { |
| 4411 | // Handle local classes which could have substituted template params. |
| 4412 | CXXRecordDecl *ClassPattern = |
| 4413 | Instantiation->isLocalClass() |
| 4414 | ? Instantiation->getInstantiatedFromMemberClass() |
| 4415 | : Instantiation->getTemplateInstantiationPattern(); |
| 4416 | |
| 4417 | DeclContext::lookup_result Lookup = |
| 4418 | ClassPattern->lookup(Name: Field->getDeclName()); |
| 4419 | FieldDecl *Pattern = Lookup.find_first<FieldDecl>(); |
| 4420 | assert(Pattern); |
| 4421 | InstantiateInClassInitializer(PointOfInstantiation, Instantiation: Field, Pattern, |
| 4422 | TemplateArgs); |
| 4423 | } |
| 4424 | } |
| 4425 | } |
| 4426 | } |
| 4427 | |
| 4428 | void |
| 4429 | Sema::InstantiateClassTemplateSpecializationMembers( |
| 4430 | SourceLocation PointOfInstantiation, |
| 4431 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
| 4432 | TemplateSpecializationKind TSK) { |
| 4433 | // C++0x [temp.explicit]p7: |
| 4434 | // An explicit instantiation that names a class template |
| 4435 | // specialization is an explicit instantion of the same kind |
| 4436 | // (declaration or definition) of each of its members (not |
| 4437 | // including members inherited from base classes) that has not |
| 4438 | // been previously explicitly specialized in the translation unit |
| 4439 | // containing the explicit instantiation, except as described |
| 4440 | // below. |
| 4441 | InstantiateClassMembers(PointOfInstantiation, Instantiation: ClassTemplateSpec, |
| 4442 | TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec), |
| 4443 | TSK); |
| 4444 | } |
| 4445 | |
| 4446 | StmtResult |
| 4447 | Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4448 | if (!S) |
| 4449 | return S; |
| 4450 | |
| 4451 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
| 4452 | SourceLocation(), |
| 4453 | DeclarationName()); |
| 4454 | return Instantiator.TransformStmt(S); |
| 4455 | } |
| 4456 | |
| 4457 | bool Sema::SubstTemplateArgument( |
| 4458 | const TemplateArgumentLoc &Input, |
| 4459 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4460 | TemplateArgumentLoc &Output, SourceLocation Loc, |
| 4461 | const DeclarationName &Entity) { |
| 4462 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); |
| 4463 | return Instantiator.TransformTemplateArgument(Input, Output); |
| 4464 | } |
| 4465 | |
| 4466 | bool Sema::SubstTemplateArguments( |
| 4467 | ArrayRef<TemplateArgumentLoc> Args, |
| 4468 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4469 | TemplateArgumentListInfo &Out) { |
| 4470 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4471 | DeclarationName()); |
| 4472 | return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out); |
| 4473 | } |
| 4474 | |
| 4475 | bool Sema::SubstTemplateArgumentsInParameterMapping( |
| 4476 | ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc, |
| 4477 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4478 | TemplateArgumentListInfo &Out) { |
| 4479 | TemplateInstantiator Instantiator( |
| 4480 | TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc, |
| 4481 | TemplateArgs); |
| 4482 | return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out); |
| 4483 | } |
| 4484 | |
| 4485 | ExprResult |
| 4486 | Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4487 | if (!E) |
| 4488 | return E; |
| 4489 | |
| 4490 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
| 4491 | SourceLocation(), |
| 4492 | DeclarationName()); |
| 4493 | return Instantiator.TransformExpr(E); |
| 4494 | } |
| 4495 | |
| 4496 | ExprResult |
| 4497 | Sema::SubstCXXIdExpr(Expr *E, |
| 4498 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4499 | if (!E) |
| 4500 | return E; |
| 4501 | |
| 4502 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4503 | DeclarationName()); |
| 4504 | return Instantiator.TransformAddressOfOperand(E); |
| 4505 | } |
| 4506 | |
| 4507 | ExprResult |
| 4508 | Sema::SubstConstraintExpr(Expr *E, |
| 4509 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4510 | if (!E) |
| 4511 | return E; |
| 4512 | |
| 4513 | TemplateInstantiator Instantiator( |
| 4514 | TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs, |
| 4515 | SourceLocation(), DeclarationName()); |
| 4516 | return Instantiator.TransformExpr(E); |
| 4517 | } |
| 4518 | |
| 4519 | ExprResult Sema::SubstConstraintExprWithoutSatisfaction( |
| 4520 | Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4521 | if (!E) |
| 4522 | return E; |
| 4523 | |
| 4524 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4525 | DeclarationName()); |
| 4526 | Instantiator.setEvaluateConstraints(false); |
| 4527 | return Instantiator.TransformExpr(E); |
| 4528 | } |
| 4529 | |
| 4530 | ExprResult Sema::SubstConceptTemplateArguments( |
| 4531 | const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr, |
| 4532 | const MultiLevelTemplateArgumentList &MLTAL) { |
| 4533 | assert(isSFINAEContext()); |
| 4534 | |
| 4535 | TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(), |
| 4536 | DeclarationName()); |
| 4537 | const ASTTemplateArgumentListInfo *ArgsAsWritten = |
| 4538 | CSE->getTemplateArgsAsWritten(); |
| 4539 | TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(), |
| 4540 | ArgsAsWritten->getRAngleLoc()); |
| 4541 | |
| 4542 | if (Instantiator.TransformConceptTemplateArguments( |
| 4543 | First: ArgsAsWritten->getTemplateArgs(), |
| 4544 | Last: ArgsAsWritten->getTemplateArgs() + |
| 4545 | ArgsAsWritten->getNumTemplateArgs(), |
| 4546 | Outputs&: SubstArgs)) |
| 4547 | return true; |
| 4548 | |
| 4549 | llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector( |
| 4550 | C: SubstArgs.arguments(), |
| 4551 | F: [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); }); |
| 4552 | |
| 4553 | MultiLevelTemplateArgumentList MLTALForConstraint = |
| 4554 | getTemplateInstantiationArgs( |
| 4555 | ND: CSE->getNamedConcept(), |
| 4556 | DC: CSE->getNamedConcept()->getLexicalDeclContext(), |
| 4557 | /*Final=*/false, |
| 4558 | /*Innermost=*/NewArgList, |
| 4559 | /*RelativeToPrimary=*/true, |
| 4560 | /*Pattern=*/nullptr, |
| 4561 | /*ForConstraintInstantiation=*/true); |
| 4562 | |
| 4563 | // Rebuild a constraint, only substituting non-dependent concept names |
| 4564 | // and nothing else. |
| 4565 | // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>. |
| 4566 | // only SomeConceptName is substituted, in the constraint expression of C. |
| 4567 | struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> { |
| 4568 | using Base = TreeTransform<ConstraintExprTransformer>; |
| 4569 | MultiLevelTemplateArgumentList &MLTAL; |
| 4570 | |
| 4571 | ConstraintExprTransformer(Sema &SemaRef, |
| 4572 | MultiLevelTemplateArgumentList &MLTAL) |
| 4573 | : TreeTransform(SemaRef), MLTAL(MLTAL) {} |
| 4574 | |
| 4575 | ExprResult TransformExpr(Expr *E) { |
| 4576 | if (!E) |
| 4577 | return E; |
| 4578 | switch (E->getStmtClass()) { |
| 4579 | case Stmt::BinaryOperatorClass: |
| 4580 | case Stmt::ConceptSpecializationExprClass: |
| 4581 | case Stmt::ParenExprClass: |
| 4582 | case Stmt::UnresolvedLookupExprClass: |
| 4583 | return Base::TransformExpr(E); |
| 4584 | default: |
| 4585 | break; |
| 4586 | } |
| 4587 | return E; |
| 4588 | } |
| 4589 | |
| 4590 | // Rebuild both branches of a conjunction / disjunction |
| 4591 | // even if there is a substitution failure in one of |
| 4592 | // the branch. |
| 4593 | ExprResult TransformBinaryOperator(BinaryOperator *E) { |
| 4594 | if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd || |
| 4595 | E->getOpcode() == BinaryOperatorKind::BO_LOr)) |
| 4596 | return E; |
| 4597 | |
| 4598 | ExprResult LHS = TransformExpr(E: E->getLHS()); |
| 4599 | ExprResult RHS = TransformExpr(E: E->getRHS()); |
| 4600 | |
| 4601 | if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS()) |
| 4602 | return E; |
| 4603 | |
| 4604 | return BinaryOperator::Create(C: SemaRef.Context, lhs: LHS.get(), rhs: RHS.get(), |
| 4605 | opc: E->getOpcode(), ResTy: SemaRef.Context.BoolTy, |
| 4606 | VK: VK_PRValue, OK: OK_Ordinary, |
| 4607 | opLoc: E->getOperatorLoc(), FPFeatures: FPOptionsOverride{}); |
| 4608 | } |
| 4609 | |
| 4610 | bool TransformTemplateArgument(const TemplateArgumentLoc &Input, |
| 4611 | TemplateArgumentLoc &Output, |
| 4612 | bool Uneval = false) { |
| 4613 | if (Input.getArgument().isConceptOrConceptTemplateParameter()) |
| 4614 | return Base::TransformTemplateArgument(Input, Output, Uneval); |
| 4615 | |
| 4616 | Output = Input; |
| 4617 | return false; |
| 4618 | } |
| 4619 | |
| 4620 | ExprResult TransformUnresolvedLookupExpr(UnresolvedLookupExpr *E, |
| 4621 | bool IsAddressOfOperand = false) { |
| 4622 | if (!E->isConceptReference()) |
| 4623 | return E; |
| 4624 | |
| 4625 | assert(E->getNumDecls() == 1 && |
| 4626 | "ConceptReference must have single declaration" ); |
| 4627 | NamedDecl *D = *E->decls_begin(); |
| 4628 | ConceptDecl *ResolvedConcept = nullptr; |
| 4629 | |
| 4630 | if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: D)) { |
| 4631 | unsigned Depth = TTP->getDepth(); |
| 4632 | unsigned Pos = TTP->getPosition(); |
| 4633 | if (Depth < MLTAL.getNumLevels() && |
| 4634 | MLTAL.hasTemplateArgument(Depth, Index: Pos)) { |
| 4635 | TemplateArgument Arg = MLTAL(Depth, Pos); |
| 4636 | assert(Arg.getKind() == TemplateArgument::Template); |
| 4637 | ResolvedConcept = |
| 4638 | dyn_cast<ConceptDecl>(Val: Arg.getAsTemplate().getAsTemplateDecl()); |
| 4639 | } |
| 4640 | if (ResolvedConcept == nullptr) |
| 4641 | return E; |
| 4642 | } else |
| 4643 | ResolvedConcept = cast<ConceptDecl>(Val: D); |
| 4644 | |
| 4645 | TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc()); |
| 4646 | if (TransformTemplateArguments(Inputs: E->getTemplateArgs(), |
| 4647 | NumInputs: E->getNumTemplateArgs(), Outputs&: TransArgs)) |
| 4648 | return ExprError(); |
| 4649 | |
| 4650 | CXXScopeSpec SS; |
| 4651 | DeclarationNameInfo NameInfo(ResolvedConcept->getDeclName(), |
| 4652 | E->getNameLoc()); |
| 4653 | return SemaRef.CheckConceptTemplateId(SS, TemplateKWLoc: SourceLocation(), ConceptNameInfo: NameInfo, |
| 4654 | FoundDecl: ResolvedConcept, NamedConcept: ResolvedConcept, |
| 4655 | TemplateArgs: &TransArgs, DoCheckConstraintSatisfaction: false); |
| 4656 | } |
| 4657 | }; |
| 4658 | |
| 4659 | ConstraintExprTransformer Transformer(*this, MLTALForConstraint); |
| 4660 | ExprResult Res = |
| 4661 | Transformer.TransformExpr(E: const_cast<Expr *>(ConstraintExpr)); |
| 4662 | return Res; |
| 4663 | } |
| 4664 | |
| 4665 | ExprResult Sema::SubstInitializer(Expr *Init, |
| 4666 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4667 | bool CXXDirectInit) { |
| 4668 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4669 | DeclarationName()); |
| 4670 | return Instantiator.TransformInitializer(Init, NotCopyInit: CXXDirectInit); |
| 4671 | } |
| 4672 | |
| 4673 | bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, |
| 4674 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4675 | SmallVectorImpl<Expr *> &Outputs) { |
| 4676 | if (Exprs.empty()) |
| 4677 | return false; |
| 4678 | |
| 4679 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
| 4680 | SourceLocation(), |
| 4681 | DeclarationName()); |
| 4682 | return Instantiator.TransformExprs(Inputs: Exprs.data(), NumInputs: Exprs.size(), |
| 4683 | IsCall, Outputs); |
| 4684 | } |
| 4685 | |
| 4686 | NestedNameSpecifierLoc |
| 4687 | Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, |
| 4688 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4689 | if (!NNS) |
| 4690 | return NestedNameSpecifierLoc(); |
| 4691 | |
| 4692 | TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), |
| 4693 | DeclarationName()); |
| 4694 | return Instantiator.TransformNestedNameSpecifierLoc(NNS); |
| 4695 | } |
| 4696 | |
| 4697 | DeclarationNameInfo |
| 4698 | Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, |
| 4699 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4700 | TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), |
| 4701 | NameInfo.getName()); |
| 4702 | return Instantiator.TransformDeclarationNameInfo(NameInfo); |
| 4703 | } |
| 4704 | |
| 4705 | TemplateName |
| 4706 | Sema::SubstTemplateName(SourceLocation TemplateKWLoc, |
| 4707 | NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, |
| 4708 | SourceLocation NameLoc, |
| 4709 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4710 | TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc, |
| 4711 | DeclarationName()); |
| 4712 | return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name, |
| 4713 | NameLoc); |
| 4714 | } |
| 4715 | |
| 4716 | static const Decl *getCanonicalParmVarDecl(const Decl *D) { |
| 4717 | // When storing ParmVarDecls in the local instantiation scope, we always |
| 4718 | // want to use the ParmVarDecl from the canonical function declaration, |
| 4719 | // since the map is then valid for any redeclaration or definition of that |
| 4720 | // function. |
| 4721 | if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: D)) { |
| 4722 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) { |
| 4723 | unsigned i = PV->getFunctionScopeIndex(); |
| 4724 | // This parameter might be from a freestanding function type within the |
| 4725 | // function and isn't necessarily referring to one of FD's parameters. |
| 4726 | if (i < FD->getNumParams() && FD->getParamDecl(i) == PV) |
| 4727 | return FD->getCanonicalDecl()->getParamDecl(i); |
| 4728 | } |
| 4729 | } |
| 4730 | return D; |
| 4731 | } |
| 4732 | |
| 4733 | llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * |
| 4734 | LocalInstantiationScope::getInstantiationOfIfExists(const Decl *D) { |
| 4735 | D = getCanonicalParmVarDecl(D); |
| 4736 | for (LocalInstantiationScope *Current = this; Current; |
| 4737 | Current = Current->Outer) { |
| 4738 | |
| 4739 | // Check if we found something within this scope. |
| 4740 | const Decl *CheckD = D; |
| 4741 | do { |
| 4742 | LocalDeclsMap::iterator Found = Current->LocalDecls.find(Val: CheckD); |
| 4743 | if (Found != Current->LocalDecls.end()) |
| 4744 | return &Found->second; |
| 4745 | |
| 4746 | // If this is a tag declaration, it's possible that we need to look for |
| 4747 | // a previous declaration. |
| 4748 | if (const TagDecl *Tag = dyn_cast<TagDecl>(Val: CheckD)) |
| 4749 | CheckD = Tag->getPreviousDecl(); |
| 4750 | else |
| 4751 | CheckD = nullptr; |
| 4752 | } while (CheckD); |
| 4753 | |
| 4754 | // If we aren't combined with our outer scope, we're done. |
| 4755 | if (!Current->CombineWithOuterScope) |
| 4756 | break; |
| 4757 | } |
| 4758 | |
| 4759 | return nullptr; |
| 4760 | } |
| 4761 | |
| 4762 | llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * |
| 4763 | LocalInstantiationScope::findInstantiationOf(const Decl *D) { |
| 4764 | auto *Result = getInstantiationOfIfExists(D); |
| 4765 | if (Result) |
| 4766 | return Result; |
| 4767 | // If we're performing a partial substitution during template argument |
| 4768 | // deduction, we may not have values for template parameters yet. |
| 4769 | if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) || |
| 4770 | isa<TemplateTemplateParmDecl>(Val: D)) |
| 4771 | return nullptr; |
| 4772 | |
| 4773 | // Local types referenced prior to definition may require instantiation. |
| 4774 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
| 4775 | if (RD->isLocalClass()) |
| 4776 | return nullptr; |
| 4777 | |
| 4778 | // Enumeration types referenced prior to definition may appear as a result of |
| 4779 | // error recovery. |
| 4780 | if (isa<EnumDecl>(Val: D)) |
| 4781 | return nullptr; |
| 4782 | |
| 4783 | // Materialized typedefs/type alias for implicit deduction guides may require |
| 4784 | // instantiation. |
| 4785 | if (isa<TypedefNameDecl>(Val: D) && |
| 4786 | isa<CXXDeductionGuideDecl>(Val: D->getDeclContext())) |
| 4787 | return nullptr; |
| 4788 | |
| 4789 | // If we didn't find the decl, then we either have a sema bug, or we have a |
| 4790 | // forward reference to a label declaration. Return null to indicate that |
| 4791 | // we have an uninstantiated label. |
| 4792 | assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope" ); |
| 4793 | return nullptr; |
| 4794 | } |
| 4795 | |
| 4796 | void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { |
| 4797 | D = getCanonicalParmVarDecl(D); |
| 4798 | llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; |
| 4799 | if (Stored.isNull()) { |
| 4800 | #ifndef NDEBUG |
| 4801 | // It should not be present in any surrounding scope either. |
| 4802 | LocalInstantiationScope *Current = this; |
| 4803 | while (Current->CombineWithOuterScope && Current->Outer) { |
| 4804 | Current = Current->Outer; |
| 4805 | assert(!Current->LocalDecls.contains(D) && |
| 4806 | "Instantiated local in inner and outer scopes" ); |
| 4807 | } |
| 4808 | #endif |
| 4809 | Stored = Inst; |
| 4810 | } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: Stored)) { |
| 4811 | Pack->push_back(Elt: cast<ValueDecl>(Val: Inst)); |
| 4812 | } else { |
| 4813 | assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local" ); |
| 4814 | } |
| 4815 | } |
| 4816 | |
| 4817 | void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, |
| 4818 | VarDecl *Inst) { |
| 4819 | D = getCanonicalParmVarDecl(D); |
| 4820 | DeclArgumentPack *Pack = cast<DeclArgumentPack *>(Val&: LocalDecls[D]); |
| 4821 | Pack->push_back(Elt: Inst); |
| 4822 | } |
| 4823 | |
| 4824 | void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { |
| 4825 | #ifndef NDEBUG |
| 4826 | // This should be the first time we've been told about this decl. |
| 4827 | for (LocalInstantiationScope *Current = this; |
| 4828 | Current && Current->CombineWithOuterScope; Current = Current->Outer) |
| 4829 | assert(!Current->LocalDecls.contains(D) && |
| 4830 | "Creating local pack after instantiation of local" ); |
| 4831 | #endif |
| 4832 | |
| 4833 | D = getCanonicalParmVarDecl(D); |
| 4834 | llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; |
| 4835 | DeclArgumentPack *Pack = new DeclArgumentPack; |
| 4836 | Stored = Pack; |
| 4837 | ArgumentPacks.push_back(Elt: Pack); |
| 4838 | } |
| 4839 | |
| 4840 | bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) { |
| 4841 | for (DeclArgumentPack *Pack : ArgumentPacks) |
| 4842 | if (llvm::is_contained(Range&: *Pack, Element: D)) |
| 4843 | return true; |
| 4844 | return false; |
| 4845 | } |
| 4846 | |
| 4847 | void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, |
| 4848 | const TemplateArgument *ExplicitArgs, |
| 4849 | unsigned NumExplicitArgs) { |
| 4850 | assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && |
| 4851 | "Already have a partially-substituted pack" ); |
| 4852 | assert((!PartiallySubstitutedPack |
| 4853 | || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && |
| 4854 | "Wrong number of arguments in partially-substituted pack" ); |
| 4855 | PartiallySubstitutedPack = Pack; |
| 4856 | ArgsInPartiallySubstitutedPack = ExplicitArgs; |
| 4857 | NumArgsInPartiallySubstitutedPack = NumExplicitArgs; |
| 4858 | } |
| 4859 | |
| 4860 | NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( |
| 4861 | const TemplateArgument **ExplicitArgs, |
| 4862 | unsigned *NumExplicitArgs) const { |
| 4863 | if (ExplicitArgs) |
| 4864 | *ExplicitArgs = nullptr; |
| 4865 | if (NumExplicitArgs) |
| 4866 | *NumExplicitArgs = 0; |
| 4867 | |
| 4868 | for (const LocalInstantiationScope *Current = this; Current; |
| 4869 | Current = Current->Outer) { |
| 4870 | if (Current->PartiallySubstitutedPack) { |
| 4871 | if (ExplicitArgs) |
| 4872 | *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; |
| 4873 | if (NumExplicitArgs) |
| 4874 | *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; |
| 4875 | |
| 4876 | return Current->PartiallySubstitutedPack; |
| 4877 | } |
| 4878 | |
| 4879 | if (!Current->CombineWithOuterScope) |
| 4880 | break; |
| 4881 | } |
| 4882 | |
| 4883 | return nullptr; |
| 4884 | } |
| 4885 | |