1 //===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===// 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 // 9 // This file provides Sema routines for C++ exception specification testing. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/SemaInternal.h" 14 #include "clang/AST/ASTMutationListener.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/Expr.h" 17 #include "clang/AST/ExprCXX.h" 18 #include "clang/AST/StmtObjC.h" 19 #include "clang/AST/TypeLoc.h" 20 #include "clang/Basic/Diagnostic.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallString.h" 24 25 namespace clang { 26 27 static const FunctionProtoType *GetUnderlyingFunction(QualType T) 28 { 29 if (const PointerType *PtrTy = T->getAs<PointerType>()) 30 T = PtrTy->getPointeeType(); 31 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>()) 32 T = RefTy->getPointeeType(); 33 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) 34 T = MPTy->getPointeeType(); 35 return T->getAs<FunctionProtoType>(); 36 } 37 38 /// HACK: 2014-11-14 libstdc++ had a bug where it shadows std::swap with a 39 /// member swap function then tries to call std::swap unqualified from the 40 /// exception specification of that function. This function detects whether 41 /// we're in such a case and turns off delay-parsing of exception 42 /// specifications. Libstdc++ 6.1 (released 2016-04-27) appears to have 43 /// resolved it as side-effect of commit ddb63209a8d (2015-06-05). 44 bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) { 45 auto *RD = dyn_cast<CXXRecordDecl>(CurContext); 46 47 // All the problem cases are member functions named "swap" within class 48 // templates declared directly within namespace std or std::__debug or 49 // std::__profile. 50 if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() || 51 !D.getIdentifier() || !D.getIdentifier()->isStr("swap")) 52 return false; 53 54 auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext()); 55 if (!ND) 56 return false; 57 58 bool IsInStd = ND->isStdNamespace(); 59 if (!IsInStd) { 60 // This isn't a direct member of namespace std, but it might still be 61 // libstdc++'s std::__debug::array or std::__profile::array. 62 IdentifierInfo *II = ND->getIdentifier(); 63 if (!II || !(II->isStr("__debug") || II->isStr("__profile")) || 64 !ND->isInStdNamespace()) 65 return false; 66 } 67 68 // Only apply this hack within a system header. 69 if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc())) 70 return false; 71 72 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName()) 73 .Case("array", true) 74 .Case("pair", IsInStd) 75 .Case("priority_queue", IsInStd) 76 .Case("stack", IsInStd) 77 .Case("queue", IsInStd) 78 .Default(false); 79 } 80 81 ExprResult Sema::ActOnNoexceptSpec(Expr *NoexceptExpr, 82 ExceptionSpecificationType &EST) { 83 84 if (NoexceptExpr->isTypeDependent() || 85 NoexceptExpr->containsUnexpandedParameterPack()) { 86 EST = EST_DependentNoexcept; 87 return NoexceptExpr; 88 } 89 90 llvm::APSInt Result; 91 ExprResult Converted = CheckConvertedConstantExpression( 92 NoexceptExpr, Context.BoolTy, Result, CCEK_Noexcept); 93 94 if (Converted.isInvalid()) { 95 EST = EST_NoexceptFalse; 96 // Fill in an expression of 'false' as a fixup. 97 auto *BoolExpr = new (Context) 98 CXXBoolLiteralExpr(false, Context.BoolTy, NoexceptExpr->getBeginLoc()); 99 llvm::APSInt Value{1}; 100 Value = 0; 101 return ConstantExpr::Create(Context, BoolExpr, APValue{Value}); 102 } 103 104 if (Converted.get()->isValueDependent()) { 105 EST = EST_DependentNoexcept; 106 return Converted; 107 } 108 109 if (!Converted.isInvalid()) 110 EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue; 111 return Converted; 112 } 113 114 /// CheckSpecifiedExceptionType - Check if the given type is valid in an 115 /// exception specification. Incomplete types, or pointers to incomplete types 116 /// other than void are not allowed. 117 /// 118 /// \param[in,out] T The exception type. This will be decayed to a pointer type 119 /// when the input is an array or a function type. 120 bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) { 121 // C++11 [except.spec]p2: 122 // A type cv T, "array of T", or "function returning T" denoted 123 // in an exception-specification is adjusted to type T, "pointer to T", or 124 // "pointer to function returning T", respectively. 125 // 126 // We also apply this rule in C++98. 127 if (T->isArrayType()) 128 T = Context.getArrayDecayedType(T); 129 else if (T->isFunctionType()) 130 T = Context.getPointerType(T); 131 132 int Kind = 0; 133 QualType PointeeT = T; 134 if (const PointerType *PT = T->getAs<PointerType>()) { 135 PointeeT = PT->getPointeeType(); 136 Kind = 1; 137 138 // cv void* is explicitly permitted, despite being a pointer to an 139 // incomplete type. 140 if (PointeeT->isVoidType()) 141 return false; 142 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 143 PointeeT = RT->getPointeeType(); 144 Kind = 2; 145 146 if (RT->isRValueReferenceType()) { 147 // C++11 [except.spec]p2: 148 // A type denoted in an exception-specification shall not denote [...] 149 // an rvalue reference type. 150 Diag(Range.getBegin(), diag::err_rref_in_exception_spec) 151 << T << Range; 152 return true; 153 } 154 } 155 156 // C++11 [except.spec]p2: 157 // A type denoted in an exception-specification shall not denote an 158 // incomplete type other than a class currently being defined [...]. 159 // A type denoted in an exception-specification shall not denote a 160 // pointer or reference to an incomplete type, other than (cv) void* or a 161 // pointer or reference to a class currently being defined. 162 // In Microsoft mode, downgrade this to a warning. 163 unsigned DiagID = diag::err_incomplete_in_exception_spec; 164 bool ReturnValueOnError = true; 165 if (getLangOpts().MSVCCompat) { 166 DiagID = diag::ext_incomplete_in_exception_spec; 167 ReturnValueOnError = false; 168 } 169 if (!(PointeeT->isRecordType() && 170 PointeeT->castAs<RecordType>()->isBeingDefined()) && 171 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range)) 172 return ReturnValueOnError; 173 174 // The MSVC compatibility mode doesn't extend to sizeless types, 175 // so diagnose them separately. 176 if (PointeeT->isSizelessType() && Kind != 1) { 177 Diag(Range.getBegin(), diag::err_sizeless_in_exception_spec) 178 << (Kind == 2 ? 1 : 0) << PointeeT << Range; 179 return true; 180 } 181 182 return false; 183 } 184 185 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer 186 /// to member to a function with an exception specification. This means that 187 /// it is invalid to add another level of indirection. 188 bool Sema::CheckDistantExceptionSpec(QualType T) { 189 // C++17 removes this rule in favor of putting exception specifications into 190 // the type system. 191 if (getLangOpts().CPlusPlus17) 192 return false; 193 194 if (const PointerType *PT = T->getAs<PointerType>()) 195 T = PT->getPointeeType(); 196 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>()) 197 T = PT->getPointeeType(); 198 else 199 return false; 200 201 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>(); 202 if (!FnT) 203 return false; 204 205 return FnT->hasExceptionSpec(); 206 } 207 208 const FunctionProtoType * 209 Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) { 210 if (FPT->getExceptionSpecType() == EST_Unparsed) { 211 Diag(Loc, diag::err_exception_spec_not_parsed); 212 return nullptr; 213 } 214 215 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 216 return FPT; 217 218 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl(); 219 const FunctionProtoType *SourceFPT = 220 SourceDecl->getType()->castAs<FunctionProtoType>(); 221 222 // If the exception specification has already been resolved, just return it. 223 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType())) 224 return SourceFPT; 225 226 // Compute or instantiate the exception specification now. 227 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated) 228 EvaluateImplicitExceptionSpec(Loc, SourceDecl); 229 else 230 InstantiateExceptionSpec(Loc, SourceDecl); 231 232 const FunctionProtoType *Proto = 233 SourceDecl->getType()->castAs<FunctionProtoType>(); 234 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) { 235 Diag(Loc, diag::err_exception_spec_not_parsed); 236 Proto = nullptr; 237 } 238 return Proto; 239 } 240 241 void 242 Sema::UpdateExceptionSpec(FunctionDecl *FD, 243 const FunctionProtoType::ExceptionSpecInfo &ESI) { 244 // If we've fully resolved the exception specification, notify listeners. 245 if (!isUnresolvedExceptionSpec(ESI.Type)) 246 if (auto *Listener = getASTMutationListener()) 247 Listener->ResolvedExceptionSpec(FD); 248 249 for (FunctionDecl *Redecl : FD->redecls()) 250 Context.adjustExceptionSpec(Redecl, ESI); 251 } 252 253 static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) { 254 auto *MD = dyn_cast<CXXMethodDecl>(FD); 255 if (!MD) 256 return false; 257 258 auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType(); 259 return EST == EST_Unparsed || 260 (EST == EST_Unevaluated && MD->getParent()->isBeingDefined()); 261 } 262 263 static bool CheckEquivalentExceptionSpecImpl( 264 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, 265 const FunctionProtoType *Old, SourceLocation OldLoc, 266 const FunctionProtoType *New, SourceLocation NewLoc, 267 bool *MissingExceptionSpecification = nullptr, 268 bool *MissingEmptyExceptionSpecification = nullptr, 269 bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false); 270 271 /// Determine whether a function has an implicitly-generated exception 272 /// specification. 273 static bool hasImplicitExceptionSpec(FunctionDecl *Decl) { 274 if (!isa<CXXDestructorDecl>(Decl) && 275 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete && 276 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 277 return false; 278 279 // For a function that the user didn't declare: 280 // - if this is a destructor, its exception specification is implicit. 281 // - if this is 'operator delete' or 'operator delete[]', the exception 282 // specification is as-if an explicit exception specification was given 283 // (per [basic.stc.dynamic]p2). 284 if (!Decl->getTypeSourceInfo()) 285 return isa<CXXDestructorDecl>(Decl); 286 287 auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 288 return !Ty->hasExceptionSpec(); 289 } 290 291 bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) { 292 // Just completely ignore this under -fno-exceptions prior to C++17. 293 // In C++17 onwards, the exception specification is part of the type and 294 // we will diagnose mismatches anyway, so it's better to check for them here. 295 if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17) 296 return false; 297 298 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator(); 299 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New; 300 bool MissingExceptionSpecification = false; 301 bool MissingEmptyExceptionSpecification = false; 302 303 unsigned DiagID = diag::err_mismatched_exception_spec; 304 bool ReturnValueOnError = true; 305 if (getLangOpts().MSVCCompat) { 306 DiagID = diag::ext_mismatched_exception_spec; 307 ReturnValueOnError = false; 308 } 309 310 // If we're befriending a member function of a class that's currently being 311 // defined, we might not be able to work out its exception specification yet. 312 // If not, defer the check until later. 313 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) { 314 DelayedEquivalentExceptionSpecChecks.push_back({New, Old}); 315 return false; 316 } 317 318 // Check the types as written: they must match before any exception 319 // specification adjustment is applied. 320 if (!CheckEquivalentExceptionSpecImpl( 321 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration), 322 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(), 323 New->getType()->getAs<FunctionProtoType>(), New->getLocation(), 324 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification, 325 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) { 326 // C++11 [except.spec]p4 [DR1492]: 327 // If a declaration of a function has an implicit 328 // exception-specification, other declarations of the function shall 329 // not specify an exception-specification. 330 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions && 331 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) { 332 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch) 333 << hasImplicitExceptionSpec(Old); 334 if (Old->getLocation().isValid()) 335 Diag(Old->getLocation(), diag::note_previous_declaration); 336 } 337 return false; 338 } 339 340 // The failure was something other than an missing exception 341 // specification; return an error, except in MS mode where this is a warning. 342 if (!MissingExceptionSpecification) 343 return ReturnValueOnError; 344 345 const FunctionProtoType *NewProto = 346 New->getType()->castAs<FunctionProtoType>(); 347 348 // The new function declaration is only missing an empty exception 349 // specification "throw()". If the throw() specification came from a 350 // function in a system header that has C linkage, just add an empty 351 // exception specification to the "new" declaration. Note that C library 352 // implementations are permitted to add these nothrow exception 353 // specifications. 354 // 355 // Likewise if the old function is a builtin. 356 if (MissingEmptyExceptionSpecification && NewProto && 357 (Old->getLocation().isInvalid() || 358 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 359 Old->getBuiltinID()) && 360 Old->isExternC()) { 361 New->setType(Context.getFunctionType( 362 NewProto->getReturnType(), NewProto->getParamTypes(), 363 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone))); 364 return false; 365 } 366 367 const FunctionProtoType *OldProto = 368 Old->getType()->castAs<FunctionProtoType>(); 369 370 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType(); 371 if (ESI.Type == EST_Dynamic) { 372 // FIXME: What if the exceptions are described in terms of the old 373 // prototype's parameters? 374 ESI.Exceptions = OldProto->exceptions(); 375 } 376 377 if (ESI.Type == EST_NoexceptFalse) 378 ESI.Type = EST_None; 379 if (ESI.Type == EST_NoexceptTrue) 380 ESI.Type = EST_BasicNoexcept; 381 382 // For dependent noexcept, we can't just take the expression from the old 383 // prototype. It likely contains references to the old prototype's parameters. 384 if (ESI.Type == EST_DependentNoexcept) { 385 New->setInvalidDecl(); 386 } else { 387 // Update the type of the function with the appropriate exception 388 // specification. 389 New->setType(Context.getFunctionType( 390 NewProto->getReturnType(), NewProto->getParamTypes(), 391 NewProto->getExtProtoInfo().withExceptionSpec(ESI))); 392 } 393 394 if (getLangOpts().MSVCCompat && isDynamicExceptionSpec(ESI.Type)) { 395 DiagID = diag::ext_missing_exception_specification; 396 ReturnValueOnError = false; 397 } else if (New->isReplaceableGlobalAllocationFunction() && 398 ESI.Type != EST_DependentNoexcept) { 399 // Allow missing exception specifications in redeclarations as an extension, 400 // when declaring a replaceable global allocation function. 401 DiagID = diag::ext_missing_exception_specification; 402 ReturnValueOnError = false; 403 } else if (ESI.Type == EST_NoThrow) { 404 // Don't emit any warning for missing 'nothrow' in MSVC. 405 if (getLangOpts().MSVCCompat) { 406 return false; 407 } 408 // Allow missing attribute 'nothrow' in redeclarations, since this is a very 409 // common omission. 410 DiagID = diag::ext_missing_exception_specification; 411 ReturnValueOnError = false; 412 } else { 413 DiagID = diag::err_missing_exception_specification; 414 ReturnValueOnError = true; 415 } 416 417 // Warn about the lack of exception specification. 418 SmallString<128> ExceptionSpecString; 419 llvm::raw_svector_ostream OS(ExceptionSpecString); 420 switch (OldProto->getExceptionSpecType()) { 421 case EST_DynamicNone: 422 OS << "throw()"; 423 break; 424 425 case EST_Dynamic: { 426 OS << "throw("; 427 bool OnFirstException = true; 428 for (const auto &E : OldProto->exceptions()) { 429 if (OnFirstException) 430 OnFirstException = false; 431 else 432 OS << ", "; 433 434 OS << E.getAsString(getPrintingPolicy()); 435 } 436 OS << ")"; 437 break; 438 } 439 440 case EST_BasicNoexcept: 441 OS << "noexcept"; 442 break; 443 444 case EST_DependentNoexcept: 445 case EST_NoexceptFalse: 446 case EST_NoexceptTrue: 447 OS << "noexcept("; 448 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr"); 449 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy()); 450 OS << ")"; 451 break; 452 case EST_NoThrow: 453 OS <<"__attribute__((nothrow))"; 454 break; 455 case EST_None: 456 case EST_MSAny: 457 case EST_Unevaluated: 458 case EST_Uninstantiated: 459 case EST_Unparsed: 460 llvm_unreachable("This spec type is compatible with none."); 461 } 462 463 SourceLocation FixItLoc; 464 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) { 465 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); 466 // FIXME: Preserve enough information so that we can produce a correct fixit 467 // location when there is a trailing return type. 468 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>()) 469 if (!FTLoc.getTypePtr()->hasTrailingReturn()) 470 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd()); 471 } 472 473 if (FixItLoc.isInvalid()) 474 Diag(New->getLocation(), DiagID) 475 << New << OS.str(); 476 else { 477 Diag(New->getLocation(), DiagID) 478 << New << OS.str() 479 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str()); 480 } 481 482 if (Old->getLocation().isValid()) 483 Diag(Old->getLocation(), diag::note_previous_declaration); 484 485 return ReturnValueOnError; 486 } 487 488 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent 489 /// exception specifications. Exception specifications are equivalent if 490 /// they allow exactly the same set of exception types. It does not matter how 491 /// that is achieved. See C++ [except.spec]p2. 492 bool Sema::CheckEquivalentExceptionSpec( 493 const FunctionProtoType *Old, SourceLocation OldLoc, 494 const FunctionProtoType *New, SourceLocation NewLoc) { 495 if (!getLangOpts().CXXExceptions) 496 return false; 497 498 unsigned DiagID = diag::err_mismatched_exception_spec; 499 if (getLangOpts().MSVCCompat) 500 DiagID = diag::ext_mismatched_exception_spec; 501 bool Result = CheckEquivalentExceptionSpecImpl( 502 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration), 503 Old, OldLoc, New, NewLoc); 504 505 // In Microsoft mode, mismatching exception specifications just cause a warning. 506 if (getLangOpts().MSVCCompat) 507 return false; 508 return Result; 509 } 510 511 /// CheckEquivalentExceptionSpec - Check if the two types have compatible 512 /// exception specifications. See C++ [except.spec]p3. 513 /// 514 /// \return \c false if the exception specifications match, \c true if there is 515 /// a problem. If \c true is returned, either a diagnostic has already been 516 /// produced or \c *MissingExceptionSpecification is set to \c true. 517 static bool CheckEquivalentExceptionSpecImpl( 518 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID, 519 const FunctionProtoType *Old, SourceLocation OldLoc, 520 const FunctionProtoType *New, SourceLocation NewLoc, 521 bool *MissingExceptionSpecification, 522 bool *MissingEmptyExceptionSpecification, 523 bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) { 524 if (MissingExceptionSpecification) 525 *MissingExceptionSpecification = false; 526 527 if (MissingEmptyExceptionSpecification) 528 *MissingEmptyExceptionSpecification = false; 529 530 Old = S.ResolveExceptionSpec(NewLoc, Old); 531 if (!Old) 532 return false; 533 New = S.ResolveExceptionSpec(NewLoc, New); 534 if (!New) 535 return false; 536 537 // C++0x [except.spec]p3: Two exception-specifications are compatible if: 538 // - both are non-throwing, regardless of their form, 539 // - both have the form noexcept(constant-expression) and the constant- 540 // expressions are equivalent, 541 // - both are dynamic-exception-specifications that have the same set of 542 // adjusted types. 543 // 544 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is 545 // of the form throw(), noexcept, or noexcept(constant-expression) where the 546 // constant-expression yields true. 547 // 548 // C++0x [except.spec]p4: If any declaration of a function has an exception- 549 // specifier that is not a noexcept-specification allowing all exceptions, 550 // all declarations [...] of that function shall have a compatible 551 // exception-specification. 552 // 553 // That last point basically means that noexcept(false) matches no spec. 554 // It's considered when AllowNoexceptAllMatchWithNoSpec is true. 555 556 ExceptionSpecificationType OldEST = Old->getExceptionSpecType(); 557 ExceptionSpecificationType NewEST = New->getExceptionSpecType(); 558 559 assert(!isUnresolvedExceptionSpec(OldEST) && 560 !isUnresolvedExceptionSpec(NewEST) && 561 "Shouldn't see unknown exception specifications here"); 562 563 CanThrowResult OldCanThrow = Old->canThrow(); 564 CanThrowResult NewCanThrow = New->canThrow(); 565 566 // Any non-throwing specifications are compatible. 567 if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot) 568 return false; 569 570 // Any throws-anything specifications are usually compatible. 571 if (OldCanThrow == CT_Can && OldEST != EST_Dynamic && 572 NewCanThrow == CT_Can && NewEST != EST_Dynamic) { 573 // The exception is that the absence of an exception specification only 574 // matches noexcept(false) for functions, as described above. 575 if (!AllowNoexceptAllMatchWithNoSpec && 576 ((OldEST == EST_None && NewEST == EST_NoexceptFalse) || 577 (OldEST == EST_NoexceptFalse && NewEST == EST_None))) { 578 // This is the disallowed case. 579 } else { 580 return false; 581 } 582 } 583 584 // C++14 [except.spec]p3: 585 // Two exception-specifications are compatible if [...] both have the form 586 // noexcept(constant-expression) and the constant-expressions are equivalent 587 if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) { 588 llvm::FoldingSetNodeID OldFSN, NewFSN; 589 Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true); 590 New->getNoexceptExpr()->Profile(NewFSN, S.Context, true); 591 if (OldFSN == NewFSN) 592 return false; 593 } 594 595 // Dynamic exception specifications with the same set of adjusted types 596 // are compatible. 597 if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) { 598 bool Success = true; 599 // Both have a dynamic exception spec. Collect the first set, then compare 600 // to the second. 601 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes; 602 for (const auto &I : Old->exceptions()) 603 OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType()); 604 605 for (const auto &I : New->exceptions()) { 606 CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType(); 607 if (OldTypes.count(TypePtr)) 608 NewTypes.insert(TypePtr); 609 else { 610 Success = false; 611 break; 612 } 613 } 614 615 if (Success && OldTypes.size() == NewTypes.size()) 616 return false; 617 } 618 619 // As a special compatibility feature, under C++0x we accept no spec and 620 // throw(std::bad_alloc) as equivalent for operator new and operator new[]. 621 // This is because the implicit declaration changed, but old code would break. 622 if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) { 623 const FunctionProtoType *WithExceptions = nullptr; 624 if (OldEST == EST_None && NewEST == EST_Dynamic) 625 WithExceptions = New; 626 else if (OldEST == EST_Dynamic && NewEST == EST_None) 627 WithExceptions = Old; 628 if (WithExceptions && WithExceptions->getNumExceptions() == 1) { 629 // One has no spec, the other throw(something). If that something is 630 // std::bad_alloc, all conditions are met. 631 QualType Exception = *WithExceptions->exception_begin(); 632 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) { 633 IdentifierInfo* Name = ExRecord->getIdentifier(); 634 if (Name && Name->getName() == "bad_alloc") { 635 // It's called bad_alloc, but is it in std? 636 if (ExRecord->isInStdNamespace()) { 637 return false; 638 } 639 } 640 } 641 } 642 } 643 644 // If the caller wants to handle the case that the new function is 645 // incompatible due to a missing exception specification, let it. 646 if (MissingExceptionSpecification && OldEST != EST_None && 647 NewEST == EST_None) { 648 // The old type has an exception specification of some sort, but 649 // the new type does not. 650 *MissingExceptionSpecification = true; 651 652 if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) { 653 // The old type has a throw() or noexcept(true) exception specification 654 // and the new type has no exception specification, and the caller asked 655 // to handle this itself. 656 *MissingEmptyExceptionSpecification = true; 657 } 658 659 return true; 660 } 661 662 S.Diag(NewLoc, DiagID); 663 if (NoteID.getDiagID() != 0 && OldLoc.isValid()) 664 S.Diag(OldLoc, NoteID); 665 return true; 666 } 667 668 bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID, 669 const PartialDiagnostic &NoteID, 670 const FunctionProtoType *Old, 671 SourceLocation OldLoc, 672 const FunctionProtoType *New, 673 SourceLocation NewLoc) { 674 if (!getLangOpts().CXXExceptions) 675 return false; 676 return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc, 677 New, NewLoc); 678 } 679 680 bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) { 681 // [except.handle]p3: 682 // A handler is a match for an exception object of type E if: 683 684 // HandlerType must be ExceptionType or derived from it, or pointer or 685 // reference to such types. 686 const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>(); 687 if (RefTy) 688 HandlerType = RefTy->getPointeeType(); 689 690 // -- the handler is of type cv T or cv T& and E and T are the same type 691 if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType)) 692 return true; 693 694 // FIXME: ObjC pointer types? 695 if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) { 696 if (RefTy && (!HandlerType.isConstQualified() || 697 HandlerType.isVolatileQualified())) 698 return false; 699 700 // -- the handler is of type cv T or const T& where T is a pointer or 701 // pointer to member type and E is std::nullptr_t 702 if (ExceptionType->isNullPtrType()) 703 return true; 704 705 // -- the handler is of type cv T or const T& where T is a pointer or 706 // pointer to member type and E is a pointer or pointer to member type 707 // that can be converted to T by one or more of 708 // -- a qualification conversion 709 // -- a function pointer conversion 710 bool LifetimeConv; 711 QualType Result; 712 // FIXME: Should we treat the exception as catchable if a lifetime 713 // conversion is required? 714 if (IsQualificationConversion(ExceptionType, HandlerType, false, 715 LifetimeConv) || 716 IsFunctionConversion(ExceptionType, HandlerType, Result)) 717 return true; 718 719 // -- a standard pointer conversion [...] 720 if (!ExceptionType->isPointerType() || !HandlerType->isPointerType()) 721 return false; 722 723 // Handle the "qualification conversion" portion. 724 Qualifiers EQuals, HQuals; 725 ExceptionType = Context.getUnqualifiedArrayType( 726 ExceptionType->getPointeeType(), EQuals); 727 HandlerType = Context.getUnqualifiedArrayType( 728 HandlerType->getPointeeType(), HQuals); 729 if (!HQuals.compatiblyIncludes(EQuals)) 730 return false; 731 732 if (HandlerType->isVoidType() && ExceptionType->isObjectType()) 733 return true; 734 735 // The only remaining case is a derived-to-base conversion. 736 } 737 738 // -- the handler is of type cg T or cv T& and T is an unambiguous public 739 // base class of E 740 if (!ExceptionType->isRecordType() || !HandlerType->isRecordType()) 741 return false; 742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 743 /*DetectVirtual=*/false); 744 if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) || 745 Paths.isAmbiguous(Context.getCanonicalType(HandlerType))) 746 return false; 747 748 // Do this check from a context without privileges. 749 switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType, 750 Paths.front(), 751 /*Diagnostic*/ 0, 752 /*ForceCheck*/ true, 753 /*ForceUnprivileged*/ true)) { 754 case AR_accessible: return true; 755 case AR_inaccessible: return false; 756 case AR_dependent: 757 llvm_unreachable("access check dependent for unprivileged context"); 758 case AR_delayed: 759 llvm_unreachable("access check delayed in non-declaration"); 760 } 761 llvm_unreachable("unexpected access check result"); 762 } 763 764 /// CheckExceptionSpecSubset - Check whether the second function type's 765 /// exception specification is a subset (or equivalent) of the first function 766 /// type. This is used by override and pointer assignment checks. 767 bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, 768 const PartialDiagnostic &NestedDiagID, 769 const PartialDiagnostic &NoteID, 770 const PartialDiagnostic &NoThrowDiagID, 771 const FunctionProtoType *Superset, 772 SourceLocation SuperLoc, 773 const FunctionProtoType *Subset, 774 SourceLocation SubLoc) { 775 776 // Just auto-succeed under -fno-exceptions. 777 if (!getLangOpts().CXXExceptions) 778 return false; 779 780 // FIXME: As usual, we could be more specific in our error messages, but 781 // that better waits until we've got types with source locations. 782 783 if (!SubLoc.isValid()) 784 SubLoc = SuperLoc; 785 786 // Resolve the exception specifications, if needed. 787 Superset = ResolveExceptionSpec(SuperLoc, Superset); 788 if (!Superset) 789 return false; 790 Subset = ResolveExceptionSpec(SubLoc, Subset); 791 if (!Subset) 792 return false; 793 794 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType(); 795 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType(); 796 assert(!isUnresolvedExceptionSpec(SuperEST) && 797 !isUnresolvedExceptionSpec(SubEST) && 798 "Shouldn't see unknown exception specifications here"); 799 800 // If there are dependent noexcept specs, assume everything is fine. Unlike 801 // with the equivalency check, this is safe in this case, because we don't 802 // want to merge declarations. Checks after instantiation will catch any 803 // omissions we make here. 804 if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept) 805 return false; 806 807 CanThrowResult SuperCanThrow = Superset->canThrow(); 808 CanThrowResult SubCanThrow = Subset->canThrow(); 809 810 // If the superset contains everything or the subset contains nothing, we're 811 // done. 812 if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) || 813 SubCanThrow == CT_Cannot) 814 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc, 815 Subset, SubLoc); 816 817 // Allow __declspec(nothrow) to be missing on redeclaration as an extension in 818 // some cases. 819 if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can && 820 SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) { 821 Diag(SubLoc, NoThrowDiagID); 822 if (NoteID.getDiagID() != 0) 823 Diag(SuperLoc, NoteID); 824 return true; 825 } 826 827 // If the subset contains everything or the superset contains nothing, we've 828 // failed. 829 if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) || 830 SuperCanThrow == CT_Cannot) { 831 Diag(SubLoc, DiagID); 832 if (NoteID.getDiagID() != 0) 833 Diag(SuperLoc, NoteID); 834 return true; 835 } 836 837 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic && 838 "Exception spec subset: non-dynamic case slipped through."); 839 840 // Neither contains everything or nothing. Do a proper comparison. 841 for (QualType SubI : Subset->exceptions()) { 842 if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>()) 843 SubI = RefTy->getPointeeType(); 844 845 // Make sure it's in the superset. 846 bool Contained = false; 847 for (QualType SuperI : Superset->exceptions()) { 848 // [except.spec]p5: 849 // the target entity shall allow at least the exceptions allowed by the 850 // source 851 // 852 // We interpret this as meaning that a handler for some target type would 853 // catch an exception of each source type. 854 if (handlerCanCatch(SuperI, SubI)) { 855 Contained = true; 856 break; 857 } 858 } 859 if (!Contained) { 860 Diag(SubLoc, DiagID); 861 if (NoteID.getDiagID() != 0) 862 Diag(SuperLoc, NoteID); 863 return true; 864 } 865 } 866 // We've run half the gauntlet. 867 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc, 868 Subset, SubLoc); 869 } 870 871 static bool 872 CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID, 873 const PartialDiagnostic &NoteID, QualType Target, 874 SourceLocation TargetLoc, QualType Source, 875 SourceLocation SourceLoc) { 876 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target); 877 if (!TFunc) 878 return false; 879 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source); 880 if (!SFunc) 881 return false; 882 883 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc, 884 SFunc, SourceLoc); 885 } 886 887 /// CheckParamExceptionSpec - Check if the parameter and return types of the 888 /// two functions have equivalent exception specs. This is part of the 889 /// assignment and override compatibility check. We do not check the parameters 890 /// of parameter function pointers recursively, as no sane programmer would 891 /// even be able to write such a function type. 892 bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID, 893 const PartialDiagnostic &NoteID, 894 const FunctionProtoType *Target, 895 SourceLocation TargetLoc, 896 const FunctionProtoType *Source, 897 SourceLocation SourceLoc) { 898 auto RetDiag = DiagID; 899 RetDiag << 0; 900 if (CheckSpecForTypesEquivalent( 901 *this, RetDiag, PDiag(), 902 Target->getReturnType(), TargetLoc, Source->getReturnType(), 903 SourceLoc)) 904 return true; 905 906 // We shouldn't even be testing this unless the arguments are otherwise 907 // compatible. 908 assert(Target->getNumParams() == Source->getNumParams() && 909 "Functions have different argument counts."); 910 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) { 911 auto ParamDiag = DiagID; 912 ParamDiag << 1; 913 if (CheckSpecForTypesEquivalent( 914 *this, ParamDiag, PDiag(), 915 Target->getParamType(i), TargetLoc, Source->getParamType(i), 916 SourceLoc)) 917 return true; 918 } 919 return false; 920 } 921 922 bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) { 923 // First we check for applicability. 924 // Target type must be a function, function pointer or function reference. 925 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType); 926 if (!ToFunc || ToFunc->hasDependentExceptionSpec()) 927 return false; 928 929 // SourceType must be a function or function pointer. 930 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType()); 931 if (!FromFunc || FromFunc->hasDependentExceptionSpec()) 932 return false; 933 934 unsigned DiagID = diag::err_incompatible_exception_specs; 935 unsigned NestedDiagID = diag::err_deep_exception_specs_differ; 936 // This is not an error in C++17 onwards, unless the noexceptness doesn't 937 // match, but in that case we have a full-on type mismatch, not just a 938 // type sugar mismatch. 939 if (getLangOpts().CPlusPlus17) { 940 DiagID = diag::warn_incompatible_exception_specs; 941 NestedDiagID = diag::warn_deep_exception_specs_differ; 942 } 943 944 // Now we've got the correct types on both sides, check their compatibility. 945 // This means that the source of the conversion can only throw a subset of 946 // the exceptions of the target, and any exception specs on arguments or 947 // return types must be equivalent. 948 // 949 // FIXME: If there is a nested dependent exception specification, we should 950 // not be checking it here. This is fine: 951 // template<typename T> void f() { 952 // void (*p)(void (*) throw(T)); 953 // void (*q)(void (*) throw(int)) = p; 954 // } 955 // ... because it might be instantiated with T=int. 956 return CheckExceptionSpecSubset( 957 PDiag(DiagID), PDiag(NestedDiagID), PDiag(), PDiag(), ToFunc, 958 From->getSourceRange().getBegin(), FromFunc, SourceLocation()) && 959 !getLangOpts().CPlusPlus17; 960 } 961 962 bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 963 const CXXMethodDecl *Old) { 964 // If the new exception specification hasn't been parsed yet, skip the check. 965 // We'll get called again once it's been parsed. 966 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() == 967 EST_Unparsed) 968 return false; 969 970 // Don't check uninstantiated template destructors at all. We can only 971 // synthesize correct specs after the template is instantiated. 972 if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType()) 973 return false; 974 975 // If the old exception specification hasn't been parsed yet, or the new 976 // exception specification can't be computed yet, remember that we need to 977 // perform this check when we get to the end of the outermost 978 // lexically-surrounding class. 979 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) { 980 DelayedOverridingExceptionSpecChecks.push_back({New, Old}); 981 return false; 982 } 983 984 unsigned DiagID = diag::err_override_exception_spec; 985 if (getLangOpts().MSVCCompat) 986 DiagID = diag::ext_override_exception_spec; 987 return CheckExceptionSpecSubset(PDiag(DiagID), 988 PDiag(diag::err_deep_exception_specs_differ), 989 PDiag(diag::note_overridden_virtual_function), 990 PDiag(diag::ext_override_exception_spec), 991 Old->getType()->castAs<FunctionProtoType>(), 992 Old->getLocation(), 993 New->getType()->castAs<FunctionProtoType>(), 994 New->getLocation()); 995 } 996 997 static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S) { 998 CanThrowResult R = CT_Cannot; 999 for (const Stmt *SubStmt : S->children()) { 1000 if (!SubStmt) 1001 continue; 1002 R = mergeCanThrow(R, Self.canThrow(SubStmt)); 1003 if (R == CT_Can) 1004 break; 1005 } 1006 return R; 1007 } 1008 1009 CanThrowResult Sema::canCalleeThrow(Sema &S, const Expr *E, const Decl *D, 1010 SourceLocation Loc) { 1011 // As an extension, we assume that __attribute__((nothrow)) functions don't 1012 // throw. 1013 if (D && isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>()) 1014 return CT_Cannot; 1015 1016 QualType T; 1017 1018 // In C++1z, just look at the function type of the callee. 1019 if (S.getLangOpts().CPlusPlus17 && E && isa<CallExpr>(E)) { 1020 E = cast<CallExpr>(E)->getCallee(); 1021 T = E->getType(); 1022 if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) { 1023 // Sadly we don't preserve the actual type as part of the "bound member" 1024 // placeholder, so we need to reconstruct it. 1025 E = E->IgnoreParenImpCasts(); 1026 1027 // Could be a call to a pointer-to-member or a plain member access. 1028 if (auto *Op = dyn_cast<BinaryOperator>(E)) { 1029 assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI); 1030 T = Op->getRHS()->getType() 1031 ->castAs<MemberPointerType>()->getPointeeType(); 1032 } else { 1033 T = cast<MemberExpr>(E)->getMemberDecl()->getType(); 1034 } 1035 } 1036 } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D)) 1037 T = VD->getType(); 1038 else 1039 // If we have no clue what we're calling, assume the worst. 1040 return CT_Can; 1041 1042 const FunctionProtoType *FT; 1043 if ((FT = T->getAs<FunctionProtoType>())) { 1044 } else if (const PointerType *PT = T->getAs<PointerType>()) 1045 FT = PT->getPointeeType()->getAs<FunctionProtoType>(); 1046 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 1047 FT = RT->getPointeeType()->getAs<FunctionProtoType>(); 1048 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>()) 1049 FT = MT->getPointeeType()->getAs<FunctionProtoType>(); 1050 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) 1051 FT = BT->getPointeeType()->getAs<FunctionProtoType>(); 1052 1053 if (!FT) 1054 return CT_Can; 1055 1056 if (Loc.isValid() || (Loc.isInvalid() && E)) 1057 FT = S.ResolveExceptionSpec(Loc.isInvalid() ? E->getBeginLoc() : Loc, FT); 1058 if (!FT) 1059 return CT_Can; 1060 1061 return FT->canThrow(); 1062 } 1063 1064 static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD) { 1065 CanThrowResult CT = CT_Cannot; 1066 1067 // Initialization might throw. 1068 if (!VD->isUsableInConstantExpressions(Self.Context)) 1069 if (const Expr *Init = VD->getInit()) 1070 CT = mergeCanThrow(CT, Self.canThrow(Init)); 1071 1072 // Destructor might throw. 1073 if (VD->needsDestruction(Self.Context) == QualType::DK_cxx_destructor) { 1074 if (auto *RD = 1075 VD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) { 1076 if (auto *Dtor = RD->getDestructor()) { 1077 CT = mergeCanThrow( 1078 CT, Sema::canCalleeThrow(Self, nullptr, Dtor, VD->getLocation())); 1079 } 1080 } 1081 } 1082 1083 // If this is a decomposition declaration, bindings might throw. 1084 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) 1085 for (auto *B : DD->bindings()) 1086 if (auto *HD = B->getHoldingVar()) 1087 CT = mergeCanThrow(CT, canVarDeclThrow(Self, HD)); 1088 1089 return CT; 1090 } 1091 1092 static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) { 1093 if (DC->isTypeDependent()) 1094 return CT_Dependent; 1095 1096 if (!DC->getTypeAsWritten()->isReferenceType()) 1097 return CT_Cannot; 1098 1099 if (DC->getSubExpr()->isTypeDependent()) 1100 return CT_Dependent; 1101 1102 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot; 1103 } 1104 1105 static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) { 1106 if (DC->isTypeOperand()) 1107 return CT_Cannot; 1108 1109 Expr *Op = DC->getExprOperand(); 1110 if (Op->isTypeDependent()) 1111 return CT_Dependent; 1112 1113 const RecordType *RT = Op->getType()->getAs<RecordType>(); 1114 if (!RT) 1115 return CT_Cannot; 1116 1117 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic()) 1118 return CT_Cannot; 1119 1120 if (Op->Classify(S.Context).isPRValue()) 1121 return CT_Cannot; 1122 1123 return CT_Can; 1124 } 1125 1126 CanThrowResult Sema::canThrow(const Stmt *S) { 1127 // C++ [expr.unary.noexcept]p3: 1128 // [Can throw] if in a potentially-evaluated context the expression would 1129 // contain: 1130 switch (S->getStmtClass()) { 1131 case Expr::ConstantExprClass: 1132 return canThrow(cast<ConstantExpr>(S)->getSubExpr()); 1133 1134 case Expr::CXXThrowExprClass: 1135 // - a potentially evaluated throw-expression 1136 return CT_Can; 1137 1138 case Expr::CXXDynamicCastExprClass: { 1139 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v), 1140 // where T is a reference type, that requires a run-time check 1141 auto *CE = cast<CXXDynamicCastExpr>(S); 1142 // FIXME: Properly determine whether a variably-modified type can throw. 1143 if (CE->getType()->isVariablyModifiedType()) 1144 return CT_Can; 1145 CanThrowResult CT = canDynamicCastThrow(CE); 1146 if (CT == CT_Can) 1147 return CT; 1148 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE)); 1149 } 1150 1151 case Expr::CXXTypeidExprClass: 1152 // - a potentially evaluated typeid expression applied to a glvalue 1153 // expression whose type is a polymorphic class type 1154 return canTypeidThrow(*this, cast<CXXTypeidExpr>(S)); 1155 1156 // - a potentially evaluated call to a function, member function, function 1157 // pointer, or member function pointer that does not have a non-throwing 1158 // exception-specification 1159 case Expr::CallExprClass: 1160 case Expr::CXXMemberCallExprClass: 1161 case Expr::CXXOperatorCallExprClass: 1162 case Expr::UserDefinedLiteralClass: { 1163 const CallExpr *CE = cast<CallExpr>(S); 1164 CanThrowResult CT; 1165 if (CE->isTypeDependent()) 1166 CT = CT_Dependent; 1167 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) 1168 CT = CT_Cannot; 1169 else 1170 CT = canCalleeThrow(*this, CE, CE->getCalleeDecl()); 1171 if (CT == CT_Can) 1172 return CT; 1173 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE)); 1174 } 1175 1176 case Expr::CXXConstructExprClass: 1177 case Expr::CXXTemporaryObjectExprClass: { 1178 auto *CE = cast<CXXConstructExpr>(S); 1179 // FIXME: Properly determine whether a variably-modified type can throw. 1180 if (CE->getType()->isVariablyModifiedType()) 1181 return CT_Can; 1182 CanThrowResult CT = canCalleeThrow(*this, CE, CE->getConstructor()); 1183 if (CT == CT_Can) 1184 return CT; 1185 return mergeCanThrow(CT, canSubStmtsThrow(*this, CE)); 1186 } 1187 1188 case Expr::CXXInheritedCtorInitExprClass: { 1189 auto *ICIE = cast<CXXInheritedCtorInitExpr>(S); 1190 return canCalleeThrow(*this, ICIE, ICIE->getConstructor()); 1191 } 1192 1193 case Expr::LambdaExprClass: { 1194 const LambdaExpr *Lambda = cast<LambdaExpr>(S); 1195 CanThrowResult CT = CT_Cannot; 1196 for (LambdaExpr::const_capture_init_iterator 1197 Cap = Lambda->capture_init_begin(), 1198 CapEnd = Lambda->capture_init_end(); 1199 Cap != CapEnd; ++Cap) 1200 CT = mergeCanThrow(CT, canThrow(*Cap)); 1201 return CT; 1202 } 1203 1204 case Expr::CXXNewExprClass: { 1205 auto *NE = cast<CXXNewExpr>(S); 1206 CanThrowResult CT; 1207 if (NE->isTypeDependent()) 1208 CT = CT_Dependent; 1209 else 1210 CT = canCalleeThrow(*this, NE, NE->getOperatorNew()); 1211 if (CT == CT_Can) 1212 return CT; 1213 return mergeCanThrow(CT, canSubStmtsThrow(*this, NE)); 1214 } 1215 1216 case Expr::CXXDeleteExprClass: { 1217 auto *DE = cast<CXXDeleteExpr>(S); 1218 CanThrowResult CT; 1219 QualType DTy = DE->getDestroyedType(); 1220 if (DTy.isNull() || DTy->isDependentType()) { 1221 CT = CT_Dependent; 1222 } else { 1223 CT = canCalleeThrow(*this, DE, DE->getOperatorDelete()); 1224 if (const RecordType *RT = DTy->getAs<RecordType>()) { 1225 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1226 const CXXDestructorDecl *DD = RD->getDestructor(); 1227 if (DD) 1228 CT = mergeCanThrow(CT, canCalleeThrow(*this, DE, DD)); 1229 } 1230 if (CT == CT_Can) 1231 return CT; 1232 } 1233 return mergeCanThrow(CT, canSubStmtsThrow(*this, DE)); 1234 } 1235 1236 case Expr::CXXBindTemporaryExprClass: { 1237 auto *BTE = cast<CXXBindTemporaryExpr>(S); 1238 // The bound temporary has to be destroyed again, which might throw. 1239 CanThrowResult CT = 1240 canCalleeThrow(*this, BTE, BTE->getTemporary()->getDestructor()); 1241 if (CT == CT_Can) 1242 return CT; 1243 return mergeCanThrow(CT, canSubStmtsThrow(*this, BTE)); 1244 } 1245 1246 case Expr::PseudoObjectExprClass: { 1247 auto *POE = cast<PseudoObjectExpr>(S); 1248 CanThrowResult CT = CT_Cannot; 1249 for (const Expr *E : POE->semantics()) { 1250 CT = mergeCanThrow(CT, canThrow(E)); 1251 if (CT == CT_Can) 1252 break; 1253 } 1254 return CT; 1255 } 1256 1257 // ObjC message sends are like function calls, but never have exception 1258 // specs. 1259 case Expr::ObjCMessageExprClass: 1260 case Expr::ObjCPropertyRefExprClass: 1261 case Expr::ObjCSubscriptRefExprClass: 1262 return CT_Can; 1263 1264 // All the ObjC literals that are implemented as calls are 1265 // potentially throwing unless we decide to close off that 1266 // possibility. 1267 case Expr::ObjCArrayLiteralClass: 1268 case Expr::ObjCDictionaryLiteralClass: 1269 case Expr::ObjCBoxedExprClass: 1270 return CT_Can; 1271 1272 // Many other things have subexpressions, so we have to test those. 1273 // Some are simple: 1274 case Expr::CoawaitExprClass: 1275 case Expr::ConditionalOperatorClass: 1276 case Expr::CoyieldExprClass: 1277 case Expr::CXXRewrittenBinaryOperatorClass: 1278 case Expr::CXXStdInitializerListExprClass: 1279 case Expr::DesignatedInitExprClass: 1280 case Expr::DesignatedInitUpdateExprClass: 1281 case Expr::ExprWithCleanupsClass: 1282 case Expr::ExtVectorElementExprClass: 1283 case Expr::InitListExprClass: 1284 case Expr::ArrayInitLoopExprClass: 1285 case Expr::MemberExprClass: 1286 case Expr::ObjCIsaExprClass: 1287 case Expr::ObjCIvarRefExprClass: 1288 case Expr::ParenExprClass: 1289 case Expr::ParenListExprClass: 1290 case Expr::ShuffleVectorExprClass: 1291 case Expr::StmtExprClass: 1292 case Expr::ConvertVectorExprClass: 1293 case Expr::VAArgExprClass: 1294 return canSubStmtsThrow(*this, S); 1295 1296 case Expr::CompoundLiteralExprClass: 1297 case Expr::CXXConstCastExprClass: 1298 case Expr::CXXAddrspaceCastExprClass: 1299 case Expr::CXXReinterpretCastExprClass: 1300 case Expr::BuiltinBitCastExprClass: 1301 // FIXME: Properly determine whether a variably-modified type can throw. 1302 if (cast<Expr>(S)->getType()->isVariablyModifiedType()) 1303 return CT_Can; 1304 return canSubStmtsThrow(*this, S); 1305 1306 // Some might be dependent for other reasons. 1307 case Expr::ArraySubscriptExprClass: 1308 case Expr::MatrixSubscriptExprClass: 1309 case Expr::OMPArraySectionExprClass: 1310 case Expr::OMPArrayShapingExprClass: 1311 case Expr::OMPIteratorExprClass: 1312 case Expr::BinaryOperatorClass: 1313 case Expr::DependentCoawaitExprClass: 1314 case Expr::CompoundAssignOperatorClass: 1315 case Expr::CStyleCastExprClass: 1316 case Expr::CXXStaticCastExprClass: 1317 case Expr::CXXFunctionalCastExprClass: 1318 case Expr::ImplicitCastExprClass: 1319 case Expr::MaterializeTemporaryExprClass: 1320 case Expr::UnaryOperatorClass: { 1321 // FIXME: Properly determine whether a variably-modified type can throw. 1322 if (auto *CE = dyn_cast<CastExpr>(S)) 1323 if (CE->getType()->isVariablyModifiedType()) 1324 return CT_Can; 1325 CanThrowResult CT = 1326 cast<Expr>(S)->isTypeDependent() ? CT_Dependent : CT_Cannot; 1327 return mergeCanThrow(CT, canSubStmtsThrow(*this, S)); 1328 } 1329 1330 case Expr::CXXDefaultArgExprClass: 1331 return canThrow(cast<CXXDefaultArgExpr>(S)->getExpr()); 1332 1333 case Expr::CXXDefaultInitExprClass: 1334 return canThrow(cast<CXXDefaultInitExpr>(S)->getExpr()); 1335 1336 case Expr::ChooseExprClass: { 1337 auto *CE = cast<ChooseExpr>(S); 1338 if (CE->isTypeDependent() || CE->isValueDependent()) 1339 return CT_Dependent; 1340 return canThrow(CE->getChosenSubExpr()); 1341 } 1342 1343 case Expr::GenericSelectionExprClass: 1344 if (cast<GenericSelectionExpr>(S)->isResultDependent()) 1345 return CT_Dependent; 1346 return canThrow(cast<GenericSelectionExpr>(S)->getResultExpr()); 1347 1348 // Some expressions are always dependent. 1349 case Expr::CXXDependentScopeMemberExprClass: 1350 case Expr::CXXUnresolvedConstructExprClass: 1351 case Expr::DependentScopeDeclRefExprClass: 1352 case Expr::CXXFoldExprClass: 1353 case Expr::RecoveryExprClass: 1354 return CT_Dependent; 1355 1356 case Expr::AsTypeExprClass: 1357 case Expr::BinaryConditionalOperatorClass: 1358 case Expr::BlockExprClass: 1359 case Expr::CUDAKernelCallExprClass: 1360 case Expr::DeclRefExprClass: 1361 case Expr::ObjCBridgedCastExprClass: 1362 case Expr::ObjCIndirectCopyRestoreExprClass: 1363 case Expr::ObjCProtocolExprClass: 1364 case Expr::ObjCSelectorExprClass: 1365 case Expr::ObjCAvailabilityCheckExprClass: 1366 case Expr::OffsetOfExprClass: 1367 case Expr::PackExpansionExprClass: 1368 case Expr::SubstNonTypeTemplateParmExprClass: 1369 case Expr::SubstNonTypeTemplateParmPackExprClass: 1370 case Expr::FunctionParmPackExprClass: 1371 case Expr::UnaryExprOrTypeTraitExprClass: 1372 case Expr::UnresolvedLookupExprClass: 1373 case Expr::UnresolvedMemberExprClass: 1374 case Expr::TypoExprClass: 1375 // FIXME: Many of the above can throw. 1376 return CT_Cannot; 1377 1378 case Expr::AddrLabelExprClass: 1379 case Expr::ArrayTypeTraitExprClass: 1380 case Expr::AtomicExprClass: 1381 case Expr::TypeTraitExprClass: 1382 case Expr::CXXBoolLiteralExprClass: 1383 case Expr::CXXNoexceptExprClass: 1384 case Expr::CXXNullPtrLiteralExprClass: 1385 case Expr::CXXPseudoDestructorExprClass: 1386 case Expr::CXXScalarValueInitExprClass: 1387 case Expr::CXXThisExprClass: 1388 case Expr::CXXUuidofExprClass: 1389 case Expr::CharacterLiteralClass: 1390 case Expr::ExpressionTraitExprClass: 1391 case Expr::FloatingLiteralClass: 1392 case Expr::GNUNullExprClass: 1393 case Expr::ImaginaryLiteralClass: 1394 case Expr::ImplicitValueInitExprClass: 1395 case Expr::IntegerLiteralClass: 1396 case Expr::FixedPointLiteralClass: 1397 case Expr::ArrayInitIndexExprClass: 1398 case Expr::NoInitExprClass: 1399 case Expr::ObjCEncodeExprClass: 1400 case Expr::ObjCStringLiteralClass: 1401 case Expr::ObjCBoolLiteralExprClass: 1402 case Expr::OpaqueValueExprClass: 1403 case Expr::PredefinedExprClass: 1404 case Expr::SizeOfPackExprClass: 1405 case Expr::StringLiteralClass: 1406 case Expr::SourceLocExprClass: 1407 case Expr::ConceptSpecializationExprClass: 1408 case Expr::RequiresExprClass: 1409 // These expressions can never throw. 1410 return CT_Cannot; 1411 1412 case Expr::MSPropertyRefExprClass: 1413 case Expr::MSPropertySubscriptExprClass: 1414 llvm_unreachable("Invalid class for expression"); 1415 1416 // Most statements can throw if any substatement can throw. 1417 case Stmt::AttributedStmtClass: 1418 case Stmt::BreakStmtClass: 1419 case Stmt::CapturedStmtClass: 1420 case Stmt::CaseStmtClass: 1421 case Stmt::CompoundStmtClass: 1422 case Stmt::ContinueStmtClass: 1423 case Stmt::CoreturnStmtClass: 1424 case Stmt::CoroutineBodyStmtClass: 1425 case Stmt::CXXCatchStmtClass: 1426 case Stmt::CXXForRangeStmtClass: 1427 case Stmt::DefaultStmtClass: 1428 case Stmt::DoStmtClass: 1429 case Stmt::ForStmtClass: 1430 case Stmt::GCCAsmStmtClass: 1431 case Stmt::GotoStmtClass: 1432 case Stmt::IndirectGotoStmtClass: 1433 case Stmt::LabelStmtClass: 1434 case Stmt::MSAsmStmtClass: 1435 case Stmt::MSDependentExistsStmtClass: 1436 case Stmt::NullStmtClass: 1437 case Stmt::ObjCAtCatchStmtClass: 1438 case Stmt::ObjCAtFinallyStmtClass: 1439 case Stmt::ObjCAtSynchronizedStmtClass: 1440 case Stmt::ObjCAutoreleasePoolStmtClass: 1441 case Stmt::ObjCForCollectionStmtClass: 1442 case Stmt::OMPAtomicDirectiveClass: 1443 case Stmt::OMPBarrierDirectiveClass: 1444 case Stmt::OMPCancelDirectiveClass: 1445 case Stmt::OMPCancellationPointDirectiveClass: 1446 case Stmt::OMPCriticalDirectiveClass: 1447 case Stmt::OMPDistributeDirectiveClass: 1448 case Stmt::OMPDistributeParallelForDirectiveClass: 1449 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 1450 case Stmt::OMPDistributeSimdDirectiveClass: 1451 case Stmt::OMPFlushDirectiveClass: 1452 case Stmt::OMPDepobjDirectiveClass: 1453 case Stmt::OMPScanDirectiveClass: 1454 case Stmt::OMPForDirectiveClass: 1455 case Stmt::OMPForSimdDirectiveClass: 1456 case Stmt::OMPMasterDirectiveClass: 1457 case Stmt::OMPMasterTaskLoopDirectiveClass: 1458 case Stmt::OMPMasterTaskLoopSimdDirectiveClass: 1459 case Stmt::OMPOrderedDirectiveClass: 1460 case Stmt::OMPCanonicalLoopClass: 1461 case Stmt::OMPParallelDirectiveClass: 1462 case Stmt::OMPParallelForDirectiveClass: 1463 case Stmt::OMPParallelForSimdDirectiveClass: 1464 case Stmt::OMPParallelMasterDirectiveClass: 1465 case Stmt::OMPParallelMasterTaskLoopDirectiveClass: 1466 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass: 1467 case Stmt::OMPParallelSectionsDirectiveClass: 1468 case Stmt::OMPSectionDirectiveClass: 1469 case Stmt::OMPSectionsDirectiveClass: 1470 case Stmt::OMPSimdDirectiveClass: 1471 case Stmt::OMPTileDirectiveClass: 1472 case Stmt::OMPUnrollDirectiveClass: 1473 case Stmt::OMPSingleDirectiveClass: 1474 case Stmt::OMPTargetDataDirectiveClass: 1475 case Stmt::OMPTargetDirectiveClass: 1476 case Stmt::OMPTargetEnterDataDirectiveClass: 1477 case Stmt::OMPTargetExitDataDirectiveClass: 1478 case Stmt::OMPTargetParallelDirectiveClass: 1479 case Stmt::OMPTargetParallelForDirectiveClass: 1480 case Stmt::OMPTargetParallelForSimdDirectiveClass: 1481 case Stmt::OMPTargetSimdDirectiveClass: 1482 case Stmt::OMPTargetTeamsDirectiveClass: 1483 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 1484 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 1485 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 1486 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 1487 case Stmt::OMPTargetUpdateDirectiveClass: 1488 case Stmt::OMPTaskDirectiveClass: 1489 case Stmt::OMPTaskgroupDirectiveClass: 1490 case Stmt::OMPTaskLoopDirectiveClass: 1491 case Stmt::OMPTaskLoopSimdDirectiveClass: 1492 case Stmt::OMPTaskwaitDirectiveClass: 1493 case Stmt::OMPTaskyieldDirectiveClass: 1494 case Stmt::OMPTeamsDirectiveClass: 1495 case Stmt::OMPTeamsDistributeDirectiveClass: 1496 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 1497 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 1498 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 1499 case Stmt::OMPInteropDirectiveClass: 1500 case Stmt::OMPDispatchDirectiveClass: 1501 case Stmt::OMPMaskedDirectiveClass: 1502 case Stmt::OMPMetaDirectiveClass: 1503 case Stmt::OMPGenericLoopDirectiveClass: 1504 case Stmt::ReturnStmtClass: 1505 case Stmt::SEHExceptStmtClass: 1506 case Stmt::SEHFinallyStmtClass: 1507 case Stmt::SEHLeaveStmtClass: 1508 case Stmt::SEHTryStmtClass: 1509 case Stmt::SwitchStmtClass: 1510 case Stmt::WhileStmtClass: 1511 return canSubStmtsThrow(*this, S); 1512 1513 case Stmt::DeclStmtClass: { 1514 CanThrowResult CT = CT_Cannot; 1515 for (const Decl *D : cast<DeclStmt>(S)->decls()) { 1516 if (auto *VD = dyn_cast<VarDecl>(D)) 1517 CT = mergeCanThrow(CT, canVarDeclThrow(*this, VD)); 1518 1519 // FIXME: Properly determine whether a variably-modified type can throw. 1520 if (auto *TND = dyn_cast<TypedefNameDecl>(D)) 1521 if (TND->getUnderlyingType()->isVariablyModifiedType()) 1522 return CT_Can; 1523 if (auto *VD = dyn_cast<ValueDecl>(D)) 1524 if (VD->getType()->isVariablyModifiedType()) 1525 return CT_Can; 1526 } 1527 return CT; 1528 } 1529 1530 case Stmt::IfStmtClass: { 1531 auto *IS = cast<IfStmt>(S); 1532 CanThrowResult CT = CT_Cannot; 1533 if (const Stmt *Init = IS->getInit()) 1534 CT = mergeCanThrow(CT, canThrow(Init)); 1535 if (const Stmt *CondDS = IS->getConditionVariableDeclStmt()) 1536 CT = mergeCanThrow(CT, canThrow(CondDS)); 1537 CT = mergeCanThrow(CT, canThrow(IS->getCond())); 1538 1539 // For 'if constexpr', consider only the non-discarded case. 1540 // FIXME: We should add a DiscardedStmt marker to the AST. 1541 if (Optional<const Stmt *> Case = IS->getNondiscardedCase(Context)) 1542 return *Case ? mergeCanThrow(CT, canThrow(*Case)) : CT; 1543 1544 CanThrowResult Then = canThrow(IS->getThen()); 1545 CanThrowResult Else = IS->getElse() ? canThrow(IS->getElse()) : CT_Cannot; 1546 if (Then == Else) 1547 return mergeCanThrow(CT, Then); 1548 1549 // For a dependent 'if constexpr', the result is dependent if it depends on 1550 // the value of the condition. 1551 return mergeCanThrow(CT, IS->isConstexpr() ? CT_Dependent 1552 : mergeCanThrow(Then, Else)); 1553 } 1554 1555 case Stmt::CXXTryStmtClass: { 1556 auto *TS = cast<CXXTryStmt>(S); 1557 // try /*...*/ catch (...) { H } can throw only if H can throw. 1558 // Any other try-catch can throw if any substatement can throw. 1559 const CXXCatchStmt *FinalHandler = TS->getHandler(TS->getNumHandlers() - 1); 1560 if (!FinalHandler->getExceptionDecl()) 1561 return canThrow(FinalHandler->getHandlerBlock()); 1562 return canSubStmtsThrow(*this, S); 1563 } 1564 1565 case Stmt::ObjCAtThrowStmtClass: 1566 return CT_Can; 1567 1568 case Stmt::ObjCAtTryStmtClass: { 1569 auto *TS = cast<ObjCAtTryStmt>(S); 1570 1571 // @catch(...) need not be last in Objective-C. Walk backwards until we 1572 // see one or hit the @try. 1573 CanThrowResult CT = CT_Cannot; 1574 if (const Stmt *Finally = TS->getFinallyStmt()) 1575 CT = mergeCanThrow(CT, canThrow(Finally)); 1576 for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) { 1577 const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I - 1); 1578 CT = mergeCanThrow(CT, canThrow(Catch)); 1579 // If we reach a @catch(...), no earlier exceptions can escape. 1580 if (Catch->hasEllipsis()) 1581 return CT; 1582 } 1583 1584 // Didn't find an @catch(...). Exceptions from the @try body can escape. 1585 return mergeCanThrow(CT, canThrow(TS->getTryBody())); 1586 } 1587 1588 case Stmt::SYCLUniqueStableNameExprClass: 1589 return CT_Cannot; 1590 case Stmt::NoStmtClass: 1591 llvm_unreachable("Invalid class for statement"); 1592 } 1593 llvm_unreachable("Bogus StmtClass"); 1594 } 1595 1596 } // end namespace clang 1597