1 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/ 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 //===----------------------------------------------------------------------===/ 7 // 8 // This file implements semantic analysis for C++0x variadic templates. 9 //===----------------------------------------------------------------------===/ 10 11 #include "clang/Sema/Sema.h" 12 #include "TypeLocBuilder.h" 13 #include "clang/AST/Expr.h" 14 #include "clang/AST/RecursiveASTVisitor.h" 15 #include "clang/AST/TypeLoc.h" 16 #include "clang/Sema/Lookup.h" 17 #include "clang/Sema/ParsedTemplate.h" 18 #include "clang/Sema/ScopeInfo.h" 19 #include "clang/Sema/SemaInternal.h" 20 #include "clang/Sema/Template.h" 21 #include <optional> 22 23 using namespace clang; 24 25 //---------------------------------------------------------------------------- 26 // Visitor that collects unexpanded parameter packs 27 //---------------------------------------------------------------------------- 28 29 namespace { 30 /// A class that collects unexpanded parameter packs. 31 class CollectUnexpandedParameterPacksVisitor : 32 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> 33 { 34 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> 35 inherited; 36 37 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded; 38 39 bool InLambda = false; 40 unsigned DepthLimit = (unsigned)-1; 41 42 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) { 43 if (auto *VD = dyn_cast<VarDecl>(ND)) { 44 // For now, the only problematic case is a generic lambda's templated 45 // call operator, so we don't need to look for all the other ways we 46 // could have reached a dependent parameter pack. 47 auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext()); 48 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr; 49 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit) 50 return; 51 } else if (getDepthAndIndex(ND).first >= DepthLimit) 52 return; 53 54 Unexpanded.push_back({ND, Loc}); 55 } 56 void addUnexpanded(const TemplateTypeParmType *T, 57 SourceLocation Loc = SourceLocation()) { 58 if (T->getDepth() < DepthLimit) 59 Unexpanded.push_back({T, Loc}); 60 } 61 62 public: 63 explicit CollectUnexpandedParameterPacksVisitor( 64 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) 65 : Unexpanded(Unexpanded) {} 66 67 bool shouldWalkTypesOfTypeLocs() const { return false; } 68 69 //------------------------------------------------------------------------ 70 // Recording occurrences of (unexpanded) parameter packs. 71 //------------------------------------------------------------------------ 72 73 /// Record occurrences of template type parameter packs. 74 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 75 if (TL.getTypePtr()->isParameterPack()) 76 addUnexpanded(TL.getTypePtr(), TL.getNameLoc()); 77 return true; 78 } 79 80 /// Record occurrences of template type parameter packs 81 /// when we don't have proper source-location information for 82 /// them. 83 /// 84 /// Ideally, this routine would never be used. 85 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) { 86 if (T->isParameterPack()) 87 addUnexpanded(T); 88 89 return true; 90 } 91 92 /// Record occurrences of function and non-type template 93 /// parameter packs in an expression. 94 bool VisitDeclRefExpr(DeclRefExpr *E) { 95 if (E->getDecl()->isParameterPack()) 96 addUnexpanded(E->getDecl(), E->getLocation()); 97 98 return true; 99 } 100 101 /// Record occurrences of template template parameter packs. 102 bool TraverseTemplateName(TemplateName Template) { 103 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>( 104 Template.getAsTemplateDecl())) { 105 if (TTP->isParameterPack()) 106 addUnexpanded(TTP); 107 } 108 109 return inherited::TraverseTemplateName(Template); 110 } 111 112 /// Suppress traversal into Objective-C container literal 113 /// elements that are pack expansions. 114 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { 115 if (!E->containsUnexpandedParameterPack()) 116 return true; 117 118 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) { 119 ObjCDictionaryElement Element = E->getKeyValueElement(I); 120 if (Element.isPackExpansion()) 121 continue; 122 123 TraverseStmt(Element.Key); 124 TraverseStmt(Element.Value); 125 } 126 return true; 127 } 128 //------------------------------------------------------------------------ 129 // Pruning the search for unexpanded parameter packs. 130 //------------------------------------------------------------------------ 131 132 /// Suppress traversal into statements and expressions that 133 /// do not contain unexpanded parameter packs. 134 bool TraverseStmt(Stmt *S) { 135 Expr *E = dyn_cast_or_null<Expr>(S); 136 if ((E && E->containsUnexpandedParameterPack()) || InLambda) 137 return inherited::TraverseStmt(S); 138 139 return true; 140 } 141 142 /// Suppress traversal into types that do not contain 143 /// unexpanded parameter packs. 144 bool TraverseType(QualType T) { 145 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda) 146 return inherited::TraverseType(T); 147 148 return true; 149 } 150 151 /// Suppress traversal into types with location information 152 /// that do not contain unexpanded parameter packs. 153 bool TraverseTypeLoc(TypeLoc TL) { 154 if ((!TL.getType().isNull() && 155 TL.getType()->containsUnexpandedParameterPack()) || 156 InLambda) 157 return inherited::TraverseTypeLoc(TL); 158 159 return true; 160 } 161 162 /// Suppress traversal of parameter packs. 163 bool TraverseDecl(Decl *D) { 164 // A function parameter pack is a pack expansion, so cannot contain 165 // an unexpanded parameter pack. Likewise for a template parameter 166 // pack that contains any references to other packs. 167 if (D && D->isParameterPack()) 168 return true; 169 170 return inherited::TraverseDecl(D); 171 } 172 173 /// Suppress traversal of pack-expanded attributes. 174 bool TraverseAttr(Attr *A) { 175 if (A->isPackExpansion()) 176 return true; 177 178 return inherited::TraverseAttr(A); 179 } 180 181 /// Suppress traversal of pack expansion expressions and types. 182 ///@{ 183 bool TraversePackExpansionType(PackExpansionType *T) { return true; } 184 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; } 185 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; } 186 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; } 187 188 ///@} 189 190 /// Suppress traversal of using-declaration pack expansion. 191 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 192 if (D->isPackExpansion()) 193 return true; 194 195 return inherited::TraverseUnresolvedUsingValueDecl(D); 196 } 197 198 /// Suppress traversal of using-declaration pack expansion. 199 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 200 if (D->isPackExpansion()) 201 return true; 202 203 return inherited::TraverseUnresolvedUsingTypenameDecl(D); 204 } 205 206 /// Suppress traversal of template argument pack expansions. 207 bool TraverseTemplateArgument(const TemplateArgument &Arg) { 208 if (Arg.isPackExpansion()) 209 return true; 210 211 return inherited::TraverseTemplateArgument(Arg); 212 } 213 214 /// Suppress traversal of template argument pack expansions. 215 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) { 216 if (ArgLoc.getArgument().isPackExpansion()) 217 return true; 218 219 return inherited::TraverseTemplateArgumentLoc(ArgLoc); 220 } 221 222 /// Suppress traversal of base specifier pack expansions. 223 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) { 224 if (Base.isPackExpansion()) 225 return true; 226 227 return inherited::TraverseCXXBaseSpecifier(Base); 228 } 229 230 /// Suppress traversal of mem-initializer pack expansions. 231 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { 232 if (Init->isPackExpansion()) 233 return true; 234 235 return inherited::TraverseConstructorInitializer(Init); 236 } 237 238 /// Note whether we're traversing a lambda containing an unexpanded 239 /// parameter pack. In this case, the unexpanded pack can occur anywhere, 240 /// including all the places where we normally wouldn't look. Within a 241 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit 242 /// outside an expression. 243 bool TraverseLambdaExpr(LambdaExpr *Lambda) { 244 // The ContainsUnexpandedParameterPack bit on a lambda is always correct, 245 // even if it's contained within another lambda. 246 if (!Lambda->containsUnexpandedParameterPack()) 247 return true; 248 249 bool WasInLambda = InLambda; 250 unsigned OldDepthLimit = DepthLimit; 251 252 InLambda = true; 253 if (auto *TPL = Lambda->getTemplateParameterList()) 254 DepthLimit = TPL->getDepth(); 255 256 inherited::TraverseLambdaExpr(Lambda); 257 258 InLambda = WasInLambda; 259 DepthLimit = OldDepthLimit; 260 return true; 261 } 262 263 /// Suppress traversal within pack expansions in lambda captures. 264 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C, 265 Expr *Init) { 266 if (C->isPackExpansion()) 267 return true; 268 269 return inherited::TraverseLambdaCapture(Lambda, C, Init); 270 } 271 }; 272 } 273 274 /// Determine whether it's possible for an unexpanded parameter pack to 275 /// be valid in this location. This only happens when we're in a declaration 276 /// that is nested within an expression that could be expanded, such as a 277 /// lambda-expression within a function call. 278 /// 279 /// This is conservatively correct, but may claim that some unexpanded packs are 280 /// permitted when they are not. 281 bool Sema::isUnexpandedParameterPackPermitted() { 282 for (auto *SI : FunctionScopes) 283 if (isa<sema::LambdaScopeInfo>(SI)) 284 return true; 285 return false; 286 } 287 288 /// Diagnose all of the unexpanded parameter packs in the given 289 /// vector. 290 bool 291 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 292 UnexpandedParameterPackContext UPPC, 293 ArrayRef<UnexpandedParameterPack> Unexpanded) { 294 if (Unexpanded.empty()) 295 return false; 296 297 // If we are within a lambda expression and referencing a pack that is not 298 // declared within the lambda itself, that lambda contains an unexpanded 299 // parameter pack, and we are done. 300 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it 301 // later. 302 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences; 303 if (auto *LSI = getEnclosingLambda()) { 304 for (auto &Pack : Unexpanded) { 305 auto DeclaresThisPack = [&](NamedDecl *LocalPack) { 306 if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) { 307 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack); 308 return TTPD && TTPD->getTypeForDecl() == TTPT; 309 } 310 return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack); 311 }; 312 if (llvm::any_of(LSI->LocalPacks, DeclaresThisPack)) 313 LambdaParamPackReferences.push_back(Pack); 314 } 315 316 if (LambdaParamPackReferences.empty()) { 317 // Construct in lambda only references packs declared outside the lambda. 318 // That's OK for now, but the lambda itself is considered to contain an 319 // unexpanded pack in this case, which will require expansion outside the 320 // lambda. 321 322 // We do not permit pack expansion that would duplicate a statement 323 // expression, not even within a lambda. 324 // FIXME: We could probably support this for statement expressions that 325 // do not contain labels. 326 // FIXME: This is insufficient to detect this problem; consider 327 // f( ({ bad: 0; }) + pack ... ); 328 bool EnclosingStmtExpr = false; 329 for (unsigned N = FunctionScopes.size(); N; --N) { 330 sema::FunctionScopeInfo *Func = FunctionScopes[N-1]; 331 if (llvm::any_of( 332 Func->CompoundScopes, 333 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) { 334 EnclosingStmtExpr = true; 335 break; 336 } 337 // Coumpound-statements outside the lambda are OK for now; we'll check 338 // for those when we finish handling the lambda. 339 if (Func == LSI) 340 break; 341 } 342 343 if (!EnclosingStmtExpr) { 344 LSI->ContainsUnexpandedParameterPack = true; 345 return false; 346 } 347 } else { 348 Unexpanded = LambdaParamPackReferences; 349 } 350 } 351 352 SmallVector<SourceLocation, 4> Locations; 353 SmallVector<IdentifierInfo *, 4> Names; 354 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown; 355 356 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 357 IdentifierInfo *Name = nullptr; 358 if (const TemplateTypeParmType *TTP 359 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) 360 Name = TTP->getIdentifier(); 361 else 362 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier(); 363 364 if (Name && NamesKnown.insert(Name).second) 365 Names.push_back(Name); 366 367 if (Unexpanded[I].second.isValid()) 368 Locations.push_back(Unexpanded[I].second); 369 } 370 371 auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack) 372 << (int)UPPC << (int)Names.size(); 373 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I) 374 DB << Names[I]; 375 376 for (unsigned I = 0, N = Locations.size(); I != N; ++I) 377 DB << SourceRange(Locations[I]); 378 return true; 379 } 380 381 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, 382 TypeSourceInfo *T, 383 UnexpandedParameterPackContext UPPC) { 384 // C++0x [temp.variadic]p5: 385 // An appearance of a name of a parameter pack that is not expanded is 386 // ill-formed. 387 if (!T->getType()->containsUnexpandedParameterPack()) 388 return false; 389 390 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 391 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc( 392 T->getTypeLoc()); 393 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 394 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded); 395 } 396 397 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E, 398 UnexpandedParameterPackContext UPPC) { 399 // C++0x [temp.variadic]p5: 400 // An appearance of a name of a parameter pack that is not expanded is 401 // ill-formed. 402 if (!E->containsUnexpandedParameterPack()) 403 return false; 404 405 // CollectUnexpandedParameterPacksVisitor does not expect to see a 406 // FunctionParmPackExpr, but diagnosing unexpected parameter packs may still 407 // see such an expression in a lambda body. 408 // We'll bail out early in this case to avoid triggering an assertion. 409 if (isa<FunctionParmPackExpr>(E) && getEnclosingLambda()) 410 return false; 411 412 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 413 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E); 414 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 415 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded); 416 } 417 418 bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) { 419 if (!RE->containsUnexpandedParameterPack()) 420 return false; 421 422 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 423 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE); 424 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 425 426 // We only care about unexpanded references to the RequiresExpr's own 427 // parameter packs. 428 auto Parms = RE->getLocalParameters(); 429 llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end()); 430 SmallVector<UnexpandedParameterPack, 2> UnexpandedParms; 431 for (auto Parm : Unexpanded) 432 if (ParmSet.contains(Parm.first.dyn_cast<NamedDecl *>())) 433 UnexpandedParms.push_back(Parm); 434 if (UnexpandedParms.empty()) 435 return false; 436 437 return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement, 438 UnexpandedParms); 439 } 440 441 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 442 UnexpandedParameterPackContext UPPC) { 443 // C++0x [temp.variadic]p5: 444 // An appearance of a name of a parameter pack that is not expanded is 445 // ill-formed. 446 if (!SS.getScopeRep() || 447 !SS.getScopeRep()->containsUnexpandedParameterPack()) 448 return false; 449 450 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 451 CollectUnexpandedParameterPacksVisitor(Unexpanded) 452 .TraverseNestedNameSpecifier(SS.getScopeRep()); 453 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 454 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(), 455 UPPC, Unexpanded); 456 } 457 458 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 459 UnexpandedParameterPackContext UPPC) { 460 // C++0x [temp.variadic]p5: 461 // An appearance of a name of a parameter pack that is not expanded is 462 // ill-formed. 463 switch (NameInfo.getName().getNameKind()) { 464 case DeclarationName::Identifier: 465 case DeclarationName::ObjCZeroArgSelector: 466 case DeclarationName::ObjCOneArgSelector: 467 case DeclarationName::ObjCMultiArgSelector: 468 case DeclarationName::CXXOperatorName: 469 case DeclarationName::CXXLiteralOperatorName: 470 case DeclarationName::CXXUsingDirective: 471 case DeclarationName::CXXDeductionGuideName: 472 return false; 473 474 case DeclarationName::CXXConstructorName: 475 case DeclarationName::CXXDestructorName: 476 case DeclarationName::CXXConversionFunctionName: 477 // FIXME: We shouldn't need this null check! 478 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo()) 479 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC); 480 481 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack()) 482 return false; 483 484 break; 485 } 486 487 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 488 CollectUnexpandedParameterPacksVisitor(Unexpanded) 489 .TraverseType(NameInfo.getName().getCXXNameType()); 490 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 491 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded); 492 } 493 494 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, 495 TemplateName Template, 496 UnexpandedParameterPackContext UPPC) { 497 498 if (Template.isNull() || !Template.containsUnexpandedParameterPack()) 499 return false; 500 501 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 502 CollectUnexpandedParameterPacksVisitor(Unexpanded) 503 .TraverseTemplateName(Template); 504 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 505 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded); 506 } 507 508 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 509 UnexpandedParameterPackContext UPPC) { 510 if (Arg.getArgument().isNull() || 511 !Arg.getArgument().containsUnexpandedParameterPack()) 512 return false; 513 514 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 515 CollectUnexpandedParameterPacksVisitor(Unexpanded) 516 .TraverseTemplateArgumentLoc(Arg); 517 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 518 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded); 519 } 520 521 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg, 522 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 523 CollectUnexpandedParameterPacksVisitor(Unexpanded) 524 .TraverseTemplateArgument(Arg); 525 } 526 527 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 528 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 529 CollectUnexpandedParameterPacksVisitor(Unexpanded) 530 .TraverseTemplateArgumentLoc(Arg); 531 } 532 533 void Sema::collectUnexpandedParameterPacks(QualType T, 534 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 535 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T); 536 } 537 538 void Sema::collectUnexpandedParameterPacks(TypeLoc TL, 539 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 540 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL); 541 } 542 543 void Sema::collectUnexpandedParameterPacks( 544 NestedNameSpecifierLoc NNS, 545 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 546 CollectUnexpandedParameterPacksVisitor(Unexpanded) 547 .TraverseNestedNameSpecifierLoc(NNS); 548 } 549 550 void Sema::collectUnexpandedParameterPacks( 551 const DeclarationNameInfo &NameInfo, 552 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 553 CollectUnexpandedParameterPacksVisitor(Unexpanded) 554 .TraverseDeclarationNameInfo(NameInfo); 555 } 556 557 558 ParsedTemplateArgument 559 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, 560 SourceLocation EllipsisLoc) { 561 if (Arg.isInvalid()) 562 return Arg; 563 564 switch (Arg.getKind()) { 565 case ParsedTemplateArgument::Type: { 566 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc); 567 if (Result.isInvalid()) 568 return ParsedTemplateArgument(); 569 570 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), 571 Arg.getLocation()); 572 } 573 574 case ParsedTemplateArgument::NonType: { 575 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc); 576 if (Result.isInvalid()) 577 return ParsedTemplateArgument(); 578 579 return ParsedTemplateArgument(Arg.getKind(), Result.get(), 580 Arg.getLocation()); 581 } 582 583 case ParsedTemplateArgument::Template: 584 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) { 585 SourceRange R(Arg.getLocation()); 586 if (Arg.getScopeSpec().isValid()) 587 R.setBegin(Arg.getScopeSpec().getBeginLoc()); 588 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 589 << R; 590 return ParsedTemplateArgument(); 591 } 592 593 return Arg.getTemplatePackExpansion(EllipsisLoc); 594 } 595 llvm_unreachable("Unhandled template argument kind?"); 596 } 597 598 TypeResult Sema::ActOnPackExpansion(ParsedType Type, 599 SourceLocation EllipsisLoc) { 600 TypeSourceInfo *TSInfo; 601 GetTypeFromParser(Type, &TSInfo); 602 if (!TSInfo) 603 return true; 604 605 TypeSourceInfo *TSResult = 606 CheckPackExpansion(TSInfo, EllipsisLoc, std::nullopt); 607 if (!TSResult) 608 return true; 609 610 return CreateParsedType(TSResult->getType(), TSResult); 611 } 612 613 TypeSourceInfo * 614 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, 615 std::optional<unsigned> NumExpansions) { 616 // Create the pack expansion type and source-location information. 617 QualType Result = CheckPackExpansion(Pattern->getType(), 618 Pattern->getTypeLoc().getSourceRange(), 619 EllipsisLoc, NumExpansions); 620 if (Result.isNull()) 621 return nullptr; 622 623 TypeLocBuilder TLB; 624 TLB.pushFullCopy(Pattern->getTypeLoc()); 625 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result); 626 TL.setEllipsisLoc(EllipsisLoc); 627 628 return TLB.getTypeSourceInfo(Context, Result); 629 } 630 631 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange, 632 SourceLocation EllipsisLoc, 633 std::optional<unsigned> NumExpansions) { 634 // C++11 [temp.variadic]p5: 635 // The pattern of a pack expansion shall name one or more 636 // parameter packs that are not expanded by a nested pack 637 // expansion. 638 // 639 // A pattern containing a deduced type can't occur "naturally" but arises in 640 // the desugaring of an init-capture pack. 641 if (!Pattern->containsUnexpandedParameterPack() && 642 !Pattern->getContainedDeducedType()) { 643 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 644 << PatternRange; 645 return QualType(); 646 } 647 648 return Context.getPackExpansionType(Pattern, NumExpansions, 649 /*ExpectPackInType=*/false); 650 } 651 652 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) { 653 return CheckPackExpansion(Pattern, EllipsisLoc, std::nullopt); 654 } 655 656 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 657 std::optional<unsigned> NumExpansions) { 658 if (!Pattern) 659 return ExprError(); 660 661 // C++0x [temp.variadic]p5: 662 // The pattern of a pack expansion shall name one or more 663 // parameter packs that are not expanded by a nested pack 664 // expansion. 665 if (!Pattern->containsUnexpandedParameterPack()) { 666 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 667 << Pattern->getSourceRange(); 668 CorrectDelayedTyposInExpr(Pattern); 669 return ExprError(); 670 } 671 672 // Create the pack expansion expression and source-location information. 673 return new (Context) 674 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions); 675 } 676 677 bool Sema::CheckParameterPacksForExpansion( 678 SourceLocation EllipsisLoc, SourceRange PatternRange, 679 ArrayRef<UnexpandedParameterPack> Unexpanded, 680 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, 681 bool &RetainExpansion, std::optional<unsigned> &NumExpansions) { 682 ShouldExpand = true; 683 RetainExpansion = false; 684 std::pair<IdentifierInfo *, SourceLocation> FirstPack; 685 bool HaveFirstPack = false; 686 std::optional<unsigned> NumPartialExpansions; 687 SourceLocation PartiallySubstitutedPackLoc; 688 689 for (UnexpandedParameterPack ParmPack : Unexpanded) { 690 // Compute the depth and index for this parameter pack. 691 unsigned Depth = 0, Index = 0; 692 IdentifierInfo *Name; 693 bool IsVarDeclPack = false; 694 695 if (const TemplateTypeParmType *TTP = 696 ParmPack.first.dyn_cast<const TemplateTypeParmType *>()) { 697 Depth = TTP->getDepth(); 698 Index = TTP->getIndex(); 699 Name = TTP->getIdentifier(); 700 } else { 701 NamedDecl *ND = ParmPack.first.get<NamedDecl *>(); 702 if (isa<VarDecl>(ND)) 703 IsVarDeclPack = true; 704 else 705 std::tie(Depth, Index) = getDepthAndIndex(ND); 706 707 Name = ND->getIdentifier(); 708 } 709 710 // Determine the size of this argument pack. 711 unsigned NewPackSize; 712 if (IsVarDeclPack) { 713 // Figure out whether we're instantiating to an argument pack or not. 714 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 715 716 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = 717 CurrentInstantiationScope->findInstantiationOf( 718 ParmPack.first.get<NamedDecl *>()); 719 if (Instantiation->is<DeclArgumentPack *>()) { 720 // We could expand this function parameter pack. 721 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size(); 722 } else { 723 // We can't expand this function parameter pack, so we can't expand 724 // the pack expansion. 725 ShouldExpand = false; 726 continue; 727 } 728 } else { 729 // If we don't have a template argument at this depth/index, then we 730 // cannot expand the pack expansion. Make a note of this, but we still 731 // want to check any parameter packs we *do* have arguments for. 732 if (Depth >= TemplateArgs.getNumLevels() || 733 !TemplateArgs.hasTemplateArgument(Depth, Index)) { 734 ShouldExpand = false; 735 continue; 736 } 737 738 // Determine the size of the argument pack. 739 NewPackSize = TemplateArgs(Depth, Index).pack_size(); 740 } 741 742 // C++0x [temp.arg.explicit]p9: 743 // Template argument deduction can extend the sequence of template 744 // arguments corresponding to a template parameter pack, even when the 745 // sequence contains explicitly specified template arguments. 746 if (!IsVarDeclPack && CurrentInstantiationScope) { 747 if (NamedDecl *PartialPack = 748 CurrentInstantiationScope->getPartiallySubstitutedPack()) { 749 unsigned PartialDepth, PartialIndex; 750 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack); 751 if (PartialDepth == Depth && PartialIndex == Index) { 752 RetainExpansion = true; 753 // We don't actually know the new pack size yet. 754 NumPartialExpansions = NewPackSize; 755 PartiallySubstitutedPackLoc = ParmPack.second; 756 continue; 757 } 758 } 759 } 760 761 if (!NumExpansions) { 762 // The is the first pack we've seen for which we have an argument. 763 // Record it. 764 NumExpansions = NewPackSize; 765 FirstPack.first = Name; 766 FirstPack.second = ParmPack.second; 767 HaveFirstPack = true; 768 continue; 769 } 770 771 if (NewPackSize != *NumExpansions) { 772 // C++0x [temp.variadic]p5: 773 // All of the parameter packs expanded by a pack expansion shall have 774 // the same number of arguments specified. 775 if (HaveFirstPack) 776 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict) 777 << FirstPack.first << Name << *NumExpansions << NewPackSize 778 << SourceRange(FirstPack.second) << SourceRange(ParmPack.second); 779 else 780 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel) 781 << Name << *NumExpansions << NewPackSize 782 << SourceRange(ParmPack.second); 783 return true; 784 } 785 } 786 787 // If we're performing a partial expansion but we also have a full expansion, 788 // expand to the number of common arguments. For example, given: 789 // 790 // template<typename ...T> struct A { 791 // template<typename ...U> void f(pair<T, U>...); 792 // }; 793 // 794 // ... a call to 'A<int, int>().f<int>' should expand the pack once and 795 // retain an expansion. 796 if (NumPartialExpansions) { 797 if (NumExpansions && *NumExpansions < *NumPartialExpansions) { 798 NamedDecl *PartialPack = 799 CurrentInstantiationScope->getPartiallySubstitutedPack(); 800 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial) 801 << PartialPack << *NumPartialExpansions << *NumExpansions 802 << SourceRange(PartiallySubstitutedPackLoc); 803 return true; 804 } 805 806 NumExpansions = NumPartialExpansions; 807 } 808 809 return false; 810 } 811 812 std::optional<unsigned> Sema::getNumArgumentsInExpansion( 813 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs) { 814 QualType Pattern = cast<PackExpansionType>(T)->getPattern(); 815 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 816 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern); 817 818 std::optional<unsigned> Result; 819 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 820 // Compute the depth and index for this parameter pack. 821 unsigned Depth; 822 unsigned Index; 823 824 if (const TemplateTypeParmType *TTP = 825 Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) { 826 Depth = TTP->getDepth(); 827 Index = TTP->getIndex(); 828 } else { 829 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>(); 830 if (isa<VarDecl>(ND)) { 831 // Function parameter pack or init-capture pack. 832 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 833 834 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = 835 CurrentInstantiationScope->findInstantiationOf( 836 Unexpanded[I].first.get<NamedDecl *>()); 837 if (Instantiation->is<Decl *>()) 838 // The pattern refers to an unexpanded pack. We're not ready to expand 839 // this pack yet. 840 return std::nullopt; 841 842 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size(); 843 assert((!Result || *Result == Size) && "inconsistent pack sizes"); 844 Result = Size; 845 continue; 846 } 847 848 std::tie(Depth, Index) = getDepthAndIndex(ND); 849 } 850 if (Depth >= TemplateArgs.getNumLevels() || 851 !TemplateArgs.hasTemplateArgument(Depth, Index)) 852 // The pattern refers to an unknown template argument. We're not ready to 853 // expand this pack yet. 854 return std::nullopt; 855 856 // Determine the size of the argument pack. 857 unsigned Size = TemplateArgs(Depth, Index).pack_size(); 858 assert((!Result || *Result == Size) && "inconsistent pack sizes"); 859 Result = Size; 860 } 861 862 return Result; 863 } 864 865 bool Sema::containsUnexpandedParameterPacks(Declarator &D) { 866 const DeclSpec &DS = D.getDeclSpec(); 867 switch (DS.getTypeSpecType()) { 868 case TST_typename: 869 case TST_typeof_unqualType: 870 case TST_typeofType: 871 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait: 872 #include "clang/Basic/TransformTypeTraits.def" 873 case TST_atomic: { 874 QualType T = DS.getRepAsType().get(); 875 if (!T.isNull() && T->containsUnexpandedParameterPack()) 876 return true; 877 break; 878 } 879 880 case TST_typeof_unqualExpr: 881 case TST_typeofExpr: 882 case TST_decltype: 883 case TST_bitint: 884 if (DS.getRepAsExpr() && 885 DS.getRepAsExpr()->containsUnexpandedParameterPack()) 886 return true; 887 break; 888 889 case TST_unspecified: 890 case TST_void: 891 case TST_char: 892 case TST_wchar: 893 case TST_char8: 894 case TST_char16: 895 case TST_char32: 896 case TST_int: 897 case TST_int128: 898 case TST_half: 899 case TST_float: 900 case TST_double: 901 case TST_Accum: 902 case TST_Fract: 903 case TST_Float16: 904 case TST_float128: 905 case TST_ibm128: 906 case TST_bool: 907 case TST_decimal32: 908 case TST_decimal64: 909 case TST_decimal128: 910 case TST_enum: 911 case TST_union: 912 case TST_struct: 913 case TST_interface: 914 case TST_class: 915 case TST_auto: 916 case TST_auto_type: 917 case TST_decltype_auto: 918 case TST_BFloat16: 919 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t: 920 #include "clang/Basic/OpenCLImageTypes.def" 921 case TST_unknown_anytype: 922 case TST_error: 923 break; 924 } 925 926 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) { 927 const DeclaratorChunk &Chunk = D.getTypeObject(I); 928 switch (Chunk.Kind) { 929 case DeclaratorChunk::Pointer: 930 case DeclaratorChunk::Reference: 931 case DeclaratorChunk::Paren: 932 case DeclaratorChunk::Pipe: 933 case DeclaratorChunk::BlockPointer: 934 // These declarator chunks cannot contain any parameter packs. 935 break; 936 937 case DeclaratorChunk::Array: 938 if (Chunk.Arr.NumElts && 939 Chunk.Arr.NumElts->containsUnexpandedParameterPack()) 940 return true; 941 break; 942 case DeclaratorChunk::Function: 943 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) { 944 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param); 945 QualType ParamTy = Param->getType(); 946 assert(!ParamTy.isNull() && "Couldn't parse type?"); 947 if (ParamTy->containsUnexpandedParameterPack()) return true; 948 } 949 950 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) { 951 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) { 952 if (Chunk.Fun.Exceptions[i] 953 .Ty.get() 954 ->containsUnexpandedParameterPack()) 955 return true; 956 } 957 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) && 958 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack()) 959 return true; 960 961 if (Chunk.Fun.hasTrailingReturnType()) { 962 QualType T = Chunk.Fun.getTrailingReturnType().get(); 963 if (!T.isNull() && T->containsUnexpandedParameterPack()) 964 return true; 965 } 966 break; 967 968 case DeclaratorChunk::MemberPointer: 969 if (Chunk.Mem.Scope().getScopeRep() && 970 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack()) 971 return true; 972 break; 973 } 974 } 975 976 if (Expr *TRC = D.getTrailingRequiresClause()) 977 if (TRC->containsUnexpandedParameterPack()) 978 return true; 979 980 return false; 981 } 982 983 namespace { 984 985 // Callback to only accept typo corrections that refer to parameter packs. 986 class ParameterPackValidatorCCC final : public CorrectionCandidateCallback { 987 public: 988 bool ValidateCandidate(const TypoCorrection &candidate) override { 989 NamedDecl *ND = candidate.getCorrectionDecl(); 990 return ND && ND->isParameterPack(); 991 } 992 993 std::unique_ptr<CorrectionCandidateCallback> clone() override { 994 return std::make_unique<ParameterPackValidatorCCC>(*this); 995 } 996 }; 997 998 } 999 1000 /// Called when an expression computing the size of a parameter pack 1001 /// is parsed. 1002 /// 1003 /// \code 1004 /// template<typename ...Types> struct count { 1005 /// static const unsigned value = sizeof...(Types); 1006 /// }; 1007 /// \endcode 1008 /// 1009 // 1010 /// \param OpLoc The location of the "sizeof" keyword. 1011 /// \param Name The name of the parameter pack whose size will be determined. 1012 /// \param NameLoc The source location of the name of the parameter pack. 1013 /// \param RParenLoc The location of the closing parentheses. 1014 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S, 1015 SourceLocation OpLoc, 1016 IdentifierInfo &Name, 1017 SourceLocation NameLoc, 1018 SourceLocation RParenLoc) { 1019 // C++0x [expr.sizeof]p5: 1020 // The identifier in a sizeof... expression shall name a parameter pack. 1021 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName); 1022 LookupName(R, S); 1023 1024 NamedDecl *ParameterPack = nullptr; 1025 switch (R.getResultKind()) { 1026 case LookupResult::Found: 1027 ParameterPack = R.getFoundDecl(); 1028 break; 1029 1030 case LookupResult::NotFound: 1031 case LookupResult::NotFoundInCurrentInstantiation: { 1032 ParameterPackValidatorCCC CCC{}; 1033 if (TypoCorrection Corrected = 1034 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr, 1035 CCC, CTK_ErrorRecovery)) { 1036 diagnoseTypo(Corrected, 1037 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name, 1038 PDiag(diag::note_parameter_pack_here)); 1039 ParameterPack = Corrected.getCorrectionDecl(); 1040 } 1041 break; 1042 } 1043 case LookupResult::FoundOverloaded: 1044 case LookupResult::FoundUnresolvedValue: 1045 break; 1046 1047 case LookupResult::Ambiguous: 1048 DiagnoseAmbiguousLookup(R); 1049 return ExprError(); 1050 } 1051 1052 if (!ParameterPack || !ParameterPack->isParameterPack()) { 1053 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name) 1054 << &Name; 1055 return ExprError(); 1056 } 1057 1058 MarkAnyDeclReferenced(OpLoc, ParameterPack, true); 1059 1060 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc, 1061 RParenLoc); 1062 } 1063 1064 TemplateArgumentLoc Sema::getTemplateArgumentPackExpansionPattern( 1065 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, 1066 std::optional<unsigned> &NumExpansions) const { 1067 const TemplateArgument &Argument = OrigLoc.getArgument(); 1068 assert(Argument.isPackExpansion()); 1069 switch (Argument.getKind()) { 1070 case TemplateArgument::Type: { 1071 // FIXME: We shouldn't ever have to worry about missing 1072 // type-source info! 1073 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo(); 1074 if (!ExpansionTSInfo) 1075 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(), 1076 Ellipsis); 1077 PackExpansionTypeLoc Expansion = 1078 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>(); 1079 Ellipsis = Expansion.getEllipsisLoc(); 1080 1081 TypeLoc Pattern = Expansion.getPatternLoc(); 1082 NumExpansions = Expansion.getTypePtr()->getNumExpansions(); 1083 1084 // We need to copy the TypeLoc because TemplateArgumentLocs store a 1085 // TypeSourceInfo. 1086 // FIXME: Find some way to avoid the copy? 1087 TypeLocBuilder TLB; 1088 TLB.pushFullCopy(Pattern); 1089 TypeSourceInfo *PatternTSInfo = 1090 TLB.getTypeSourceInfo(Context, Pattern.getType()); 1091 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()), 1092 PatternTSInfo); 1093 } 1094 1095 case TemplateArgument::Expression: { 1096 PackExpansionExpr *Expansion 1097 = cast<PackExpansionExpr>(Argument.getAsExpr()); 1098 Expr *Pattern = Expansion->getPattern(); 1099 Ellipsis = Expansion->getEllipsisLoc(); 1100 NumExpansions = Expansion->getNumExpansions(); 1101 return TemplateArgumentLoc(Pattern, Pattern); 1102 } 1103 1104 case TemplateArgument::TemplateExpansion: 1105 Ellipsis = OrigLoc.getTemplateEllipsisLoc(); 1106 NumExpansions = Argument.getNumTemplateExpansions(); 1107 return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(), 1108 OrigLoc.getTemplateQualifierLoc(), 1109 OrigLoc.getTemplateNameLoc()); 1110 1111 case TemplateArgument::Declaration: 1112 case TemplateArgument::NullPtr: 1113 case TemplateArgument::Template: 1114 case TemplateArgument::Integral: 1115 case TemplateArgument::Pack: 1116 case TemplateArgument::Null: 1117 return TemplateArgumentLoc(); 1118 } 1119 1120 llvm_unreachable("Invalid TemplateArgument Kind!"); 1121 } 1122 1123 std::optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) { 1124 assert(Arg.containsUnexpandedParameterPack()); 1125 1126 // If this is a substituted pack, grab that pack. If not, we don't know 1127 // the size yet. 1128 // FIXME: We could find a size in more cases by looking for a substituted 1129 // pack anywhere within this argument, but that's not necessary in the common 1130 // case for 'sizeof...(A)' handling. 1131 TemplateArgument Pack; 1132 switch (Arg.getKind()) { 1133 case TemplateArgument::Type: 1134 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>()) 1135 Pack = Subst->getArgumentPack(); 1136 else 1137 return std::nullopt; 1138 break; 1139 1140 case TemplateArgument::Expression: 1141 if (auto *Subst = 1142 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr())) 1143 Pack = Subst->getArgumentPack(); 1144 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) { 1145 for (VarDecl *PD : *Subst) 1146 if (PD->isParameterPack()) 1147 return std::nullopt; 1148 return Subst->getNumExpansions(); 1149 } else 1150 return std::nullopt; 1151 break; 1152 1153 case TemplateArgument::Template: 1154 if (SubstTemplateTemplateParmPackStorage *Subst = 1155 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack()) 1156 Pack = Subst->getArgumentPack(); 1157 else 1158 return std::nullopt; 1159 break; 1160 1161 case TemplateArgument::Declaration: 1162 case TemplateArgument::NullPtr: 1163 case TemplateArgument::TemplateExpansion: 1164 case TemplateArgument::Integral: 1165 case TemplateArgument::Pack: 1166 case TemplateArgument::Null: 1167 return std::nullopt; 1168 } 1169 1170 // Check that no argument in the pack is itself a pack expansion. 1171 for (TemplateArgument Elem : Pack.pack_elements()) { 1172 // There's no point recursing in this case; we would have already 1173 // expanded this pack expansion into the enclosing pack if we could. 1174 if (Elem.isPackExpansion()) 1175 return std::nullopt; 1176 } 1177 return Pack.pack_size(); 1178 } 1179 1180 static void CheckFoldOperand(Sema &S, Expr *E) { 1181 if (!E) 1182 return; 1183 1184 E = E->IgnoreImpCasts(); 1185 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 1186 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) || 1187 isa<AbstractConditionalOperator>(E)) { 1188 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand) 1189 << E->getSourceRange() 1190 << FixItHint::CreateInsertion(E->getBeginLoc(), "(") 1191 << FixItHint::CreateInsertion(E->getEndLoc(), ")"); 1192 } 1193 } 1194 1195 ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, 1196 tok::TokenKind Operator, 1197 SourceLocation EllipsisLoc, Expr *RHS, 1198 SourceLocation RParenLoc) { 1199 // LHS and RHS must be cast-expressions. We allow an arbitrary expression 1200 // in the parser and reduce down to just cast-expressions here. 1201 CheckFoldOperand(*this, LHS); 1202 CheckFoldOperand(*this, RHS); 1203 1204 auto DiscardOperands = [&] { 1205 CorrectDelayedTyposInExpr(LHS); 1206 CorrectDelayedTyposInExpr(RHS); 1207 }; 1208 1209 // [expr.prim.fold]p3: 1210 // In a binary fold, op1 and op2 shall be the same fold-operator, and 1211 // either e1 shall contain an unexpanded parameter pack or e2 shall contain 1212 // an unexpanded parameter pack, but not both. 1213 if (LHS && RHS && 1214 LHS->containsUnexpandedParameterPack() == 1215 RHS->containsUnexpandedParameterPack()) { 1216 DiscardOperands(); 1217 return Diag(EllipsisLoc, 1218 LHS->containsUnexpandedParameterPack() 1219 ? diag::err_fold_expression_packs_both_sides 1220 : diag::err_pack_expansion_without_parameter_packs) 1221 << LHS->getSourceRange() << RHS->getSourceRange(); 1222 } 1223 1224 // [expr.prim.fold]p2: 1225 // In a unary fold, the cast-expression shall contain an unexpanded 1226 // parameter pack. 1227 if (!LHS || !RHS) { 1228 Expr *Pack = LHS ? LHS : RHS; 1229 assert(Pack && "fold expression with neither LHS nor RHS"); 1230 if (!Pack->containsUnexpandedParameterPack()) { 1231 DiscardOperands(); 1232 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1233 << Pack->getSourceRange(); 1234 } 1235 } 1236 1237 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator); 1238 1239 // Perform first-phase name lookup now. 1240 UnresolvedLookupExpr *ULE = nullptr; 1241 { 1242 UnresolvedSet<16> Functions; 1243 LookupBinOp(S, EllipsisLoc, Opc, Functions); 1244 if (!Functions.empty()) { 1245 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName( 1246 BinaryOperator::getOverloadedOperator(Opc)); 1247 ExprResult Callee = CreateUnresolvedLookupExpr( 1248 /*NamingClass*/ nullptr, NestedNameSpecifierLoc(), 1249 DeclarationNameInfo(OpName, EllipsisLoc), Functions); 1250 if (Callee.isInvalid()) 1251 return ExprError(); 1252 ULE = cast<UnresolvedLookupExpr>(Callee.get()); 1253 } 1254 } 1255 1256 return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc, 1257 std::nullopt); 1258 } 1259 1260 ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, 1261 SourceLocation LParenLoc, Expr *LHS, 1262 BinaryOperatorKind Operator, 1263 SourceLocation EllipsisLoc, Expr *RHS, 1264 SourceLocation RParenLoc, 1265 std::optional<unsigned> NumExpansions) { 1266 return new (Context) 1267 CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator, 1268 EllipsisLoc, RHS, RParenLoc, NumExpansions); 1269 } 1270 1271 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 1272 BinaryOperatorKind Operator) { 1273 // [temp.variadic]p9: 1274 // If N is zero for a unary fold-expression, the value of the expression is 1275 // && -> true 1276 // || -> false 1277 // , -> void() 1278 // if the operator is not listed [above], the instantiation is ill-formed. 1279 // 1280 // Note that we need to use something like int() here, not merely 0, to 1281 // prevent the result from being a null pointer constant. 1282 QualType ScalarType; 1283 switch (Operator) { 1284 case BO_LOr: 1285 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false); 1286 case BO_LAnd: 1287 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true); 1288 case BO_Comma: 1289 ScalarType = Context.VoidTy; 1290 break; 1291 1292 default: 1293 return Diag(EllipsisLoc, diag::err_fold_expression_empty) 1294 << BinaryOperator::getOpcodeStr(Operator); 1295 } 1296 1297 return new (Context) CXXScalarValueInitExpr( 1298 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc), 1299 EllipsisLoc); 1300 } 1301