1 //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- 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 defines analysis_warnings::[Policy,Executor]. 10 // Together they are used by Sema to issue warnings based on inexpensive 11 // static analysis algorithms in libAnalysis. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Sema/AnalysisBasedWarnings.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/EvaluatedExprVisitor.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/ParentMap.h" 22 #include "clang/AST/RecursiveASTVisitor.h" 23 #include "clang/AST/StmtCXX.h" 24 #include "clang/AST/StmtObjC.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h" 27 #include "clang/Analysis/Analyses/Consumed.h" 28 #include "clang/Analysis/Analyses/ReachableCode.h" 29 #include "clang/Analysis/Analyses/ThreadSafety.h" 30 #include "clang/Analysis/Analyses/UninitializedValues.h" 31 #include "clang/Analysis/AnalysisDeclContext.h" 32 #include "clang/Analysis/CFG.h" 33 #include "clang/Analysis/CFGStmtMap.h" 34 #include "clang/Basic/SourceLocation.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Lex/Preprocessor.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "llvm/ADT/BitVector.h" 40 #include "llvm/ADT/MapVector.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/SmallVector.h" 43 #include "llvm/ADT/StringRef.h" 44 #include "llvm/Support/Casting.h" 45 #include <algorithm> 46 #include <deque> 47 #include <iterator> 48 49 using namespace clang; 50 51 //===----------------------------------------------------------------------===// 52 // Unreachable code analysis. 53 //===----------------------------------------------------------------------===// 54 55 namespace { 56 class UnreachableCodeHandler : public reachable_code::Callback { 57 Sema &S; 58 SourceRange PreviousSilenceableCondVal; 59 60 public: 61 UnreachableCodeHandler(Sema &s) : S(s) {} 62 63 void HandleUnreachable(reachable_code::UnreachableKind UK, 64 SourceLocation L, 65 SourceRange SilenceableCondVal, 66 SourceRange R1, 67 SourceRange R2) override { 68 // Avoid reporting multiple unreachable code diagnostics that are 69 // triggered by the same conditional value. 70 if (PreviousSilenceableCondVal.isValid() && 71 SilenceableCondVal.isValid() && 72 PreviousSilenceableCondVal == SilenceableCondVal) 73 return; 74 PreviousSilenceableCondVal = SilenceableCondVal; 75 76 unsigned diag = diag::warn_unreachable; 77 switch (UK) { 78 case reachable_code::UK_Break: 79 diag = diag::warn_unreachable_break; 80 break; 81 case reachable_code::UK_Return: 82 diag = diag::warn_unreachable_return; 83 break; 84 case reachable_code::UK_Loop_Increment: 85 diag = diag::warn_unreachable_loop_increment; 86 break; 87 case reachable_code::UK_Other: 88 break; 89 } 90 91 S.Diag(L, diag) << R1 << R2; 92 93 SourceLocation Open = SilenceableCondVal.getBegin(); 94 if (Open.isValid()) { 95 SourceLocation Close = SilenceableCondVal.getEnd(); 96 Close = S.getLocForEndOfToken(Close); 97 if (Close.isValid()) { 98 S.Diag(Open, diag::note_unreachable_silence) 99 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (") 100 << FixItHint::CreateInsertion(Close, ")"); 101 } 102 } 103 } 104 }; 105 } // anonymous namespace 106 107 /// CheckUnreachable - Check for unreachable code. 108 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) { 109 // As a heuristic prune all diagnostics not in the main file. Currently 110 // the majority of warnings in headers are false positives. These 111 // are largely caused by configuration state, e.g. preprocessor 112 // defined code, etc. 113 // 114 // Note that this is also a performance optimization. Analyzing 115 // headers many times can be expensive. 116 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc())) 117 return; 118 119 UnreachableCodeHandler UC(S); 120 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC); 121 } 122 123 namespace { 124 /// Warn on logical operator errors in CFGBuilder 125 class LogicalErrorHandler : public CFGCallback { 126 Sema &S; 127 128 public: 129 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {} 130 131 static bool HasMacroID(const Expr *E) { 132 if (E->getExprLoc().isMacroID()) 133 return true; 134 135 // Recurse to children. 136 for (const Stmt *SubStmt : E->children()) 137 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt)) 138 if (HasMacroID(SubExpr)) 139 return true; 140 141 return false; 142 } 143 144 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override { 145 if (HasMacroID(B)) 146 return; 147 148 SourceRange DiagRange = B->getSourceRange(); 149 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison) 150 << DiagRange << isAlwaysTrue; 151 } 152 153 void compareBitwiseEquality(const BinaryOperator *B, 154 bool isAlwaysTrue) override { 155 if (HasMacroID(B)) 156 return; 157 158 SourceRange DiagRange = B->getSourceRange(); 159 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always) 160 << DiagRange << isAlwaysTrue; 161 } 162 }; 163 } // anonymous namespace 164 165 //===----------------------------------------------------------------------===// 166 // Check for infinite self-recursion in functions 167 //===----------------------------------------------------------------------===// 168 169 // Returns true if the function is called anywhere within the CFGBlock. 170 // For member functions, the additional condition of being call from the 171 // this pointer is required. 172 static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) { 173 // Process all the Stmt's in this block to find any calls to FD. 174 for (const auto &B : Block) { 175 if (B.getKind() != CFGElement::Statement) 176 continue; 177 178 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt()); 179 if (!CE || !CE->getCalleeDecl() || 180 CE->getCalleeDecl()->getCanonicalDecl() != FD) 181 continue; 182 183 // Skip function calls which are qualified with a templated class. 184 if (const DeclRefExpr *DRE = 185 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) { 186 if (NestedNameSpecifier *NNS = DRE->getQualifier()) { 187 if (NNS->getKind() == NestedNameSpecifier::TypeSpec && 188 isa<TemplateSpecializationType>(NNS->getAsType())) { 189 continue; 190 } 191 } 192 } 193 194 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE); 195 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) || 196 !MCE->getMethodDecl()->isVirtual()) 197 return true; 198 } 199 return false; 200 } 201 202 // Returns true if every path from the entry block passes through a call to FD. 203 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) { 204 llvm::SmallPtrSet<CFGBlock *, 16> Visited; 205 llvm::SmallVector<CFGBlock *, 16> WorkList; 206 // Keep track of whether we found at least one recursive path. 207 bool foundRecursion = false; 208 209 const unsigned ExitID = cfg->getExit().getBlockID(); 210 211 // Seed the work list with the entry block. 212 WorkList.push_back(&cfg->getEntry()); 213 214 while (!WorkList.empty()) { 215 CFGBlock *Block = WorkList.pop_back_val(); 216 217 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) { 218 if (CFGBlock *SuccBlock = *I) { 219 if (!Visited.insert(SuccBlock).second) 220 continue; 221 222 // Found a path to the exit node without a recursive call. 223 if (ExitID == SuccBlock->getBlockID()) 224 return false; 225 226 // If the successor block contains a recursive call, end analysis there. 227 if (hasRecursiveCallInPath(FD, *SuccBlock)) { 228 foundRecursion = true; 229 continue; 230 } 231 232 WorkList.push_back(SuccBlock); 233 } 234 } 235 } 236 return foundRecursion; 237 } 238 239 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD, 240 const Stmt *Body, AnalysisDeclContext &AC) { 241 FD = FD->getCanonicalDecl(); 242 243 // Only run on non-templated functions and non-templated members of 244 // templated classes. 245 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate && 246 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization) 247 return; 248 249 CFG *cfg = AC.getCFG(); 250 if (!cfg) return; 251 252 // If the exit block is unreachable, skip processing the function. 253 if (cfg->getExit().pred_empty()) 254 return; 255 256 // Emit diagnostic if a recursive function call is detected for all paths. 257 if (checkForRecursiveFunctionCall(FD, cfg)) 258 S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function); 259 } 260 261 //===----------------------------------------------------------------------===// 262 // Check for throw in a non-throwing function. 263 //===----------------------------------------------------------------------===// 264 265 /// Determine whether an exception thrown by E, unwinding from ThrowBlock, 266 /// can reach ExitBlock. 267 static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock, 268 CFG *Body) { 269 SmallVector<CFGBlock *, 16> Stack; 270 llvm::BitVector Queued(Body->getNumBlockIDs()); 271 272 Stack.push_back(&ThrowBlock); 273 Queued[ThrowBlock.getBlockID()] = true; 274 275 while (!Stack.empty()) { 276 CFGBlock &UnwindBlock = *Stack.back(); 277 Stack.pop_back(); 278 279 for (auto &Succ : UnwindBlock.succs()) { 280 if (!Succ.isReachable() || Queued[Succ->getBlockID()]) 281 continue; 282 283 if (Succ->getBlockID() == Body->getExit().getBlockID()) 284 return true; 285 286 if (auto *Catch = 287 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) { 288 QualType Caught = Catch->getCaughtType(); 289 if (Caught.isNull() || // catch (...) catches everything 290 !E->getSubExpr() || // throw; is considered cuaght by any handler 291 S.handlerCanCatch(Caught, E->getSubExpr()->getType())) 292 // Exception doesn't escape via this path. 293 break; 294 } else { 295 Stack.push_back(Succ); 296 Queued[Succ->getBlockID()] = true; 297 } 298 } 299 } 300 301 return false; 302 } 303 304 static void visitReachableThrows( 305 CFG *BodyCFG, 306 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) { 307 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs()); 308 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable); 309 for (CFGBlock *B : *BodyCFG) { 310 if (!Reachable[B->getBlockID()]) 311 continue; 312 for (CFGElement &E : *B) { 313 Optional<CFGStmt> S = E.getAs<CFGStmt>(); 314 if (!S) 315 continue; 316 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt())) 317 Visit(Throw, *B); 318 } 319 } 320 } 321 322 static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc, 323 const FunctionDecl *FD) { 324 if (!S.getSourceManager().isInSystemHeader(OpLoc) && 325 FD->getTypeSourceInfo()) { 326 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD; 327 if (S.getLangOpts().CPlusPlus11 && 328 (isa<CXXDestructorDecl>(FD) || 329 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete || 330 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) { 331 if (const auto *Ty = FD->getTypeSourceInfo()->getType()-> 332 getAs<FunctionProtoType>()) 333 S.Diag(FD->getLocation(), diag::note_throw_in_dtor) 334 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec() 335 << FD->getExceptionSpecSourceRange(); 336 } else 337 S.Diag(FD->getLocation(), diag::note_throw_in_function) 338 << FD->getExceptionSpecSourceRange(); 339 } 340 } 341 342 static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD, 343 AnalysisDeclContext &AC) { 344 CFG *BodyCFG = AC.getCFG(); 345 if (!BodyCFG) 346 return; 347 if (BodyCFG->getExit().pred_empty()) 348 return; 349 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) { 350 if (throwEscapes(S, Throw, Block, BodyCFG)) 351 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD); 352 }); 353 } 354 355 static bool isNoexcept(const FunctionDecl *FD) { 356 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 357 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>()) 358 return true; 359 return false; 360 } 361 362 //===----------------------------------------------------------------------===// 363 // Check for missing return value. 364 //===----------------------------------------------------------------------===// 365 366 enum ControlFlowKind { 367 UnknownFallThrough, 368 NeverFallThrough, 369 MaybeFallThrough, 370 AlwaysFallThrough, 371 NeverFallThroughOrReturn 372 }; 373 374 /// CheckFallThrough - Check that we don't fall off the end of a 375 /// Statement that should return a value. 376 /// 377 /// \returns AlwaysFallThrough iff we always fall off the end of the statement, 378 /// MaybeFallThrough iff we might or might not fall off the end, 379 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or 380 /// return. We assume NeverFallThrough iff we never fall off the end of the 381 /// statement but we may return. We assume that functions not marked noreturn 382 /// will return. 383 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) { 384 CFG *cfg = AC.getCFG(); 385 if (!cfg) return UnknownFallThrough; 386 387 // The CFG leaves in dead things, and we don't want the dead code paths to 388 // confuse us, so we mark all live things first. 389 llvm::BitVector live(cfg->getNumBlockIDs()); 390 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(), 391 live); 392 393 bool AddEHEdges = AC.getAddEHEdges(); 394 if (!AddEHEdges && count != cfg->getNumBlockIDs()) 395 // When there are things remaining dead, and we didn't add EH edges 396 // from CallExprs to the catch clauses, we have to go back and 397 // mark them as live. 398 for (const auto *B : *cfg) { 399 if (!live[B->getBlockID()]) { 400 if (B->pred_begin() == B->pred_end()) { 401 const Stmt *Term = B->getTerminatorStmt(); 402 if (Term && isa<CXXTryStmt>(Term)) 403 // When not adding EH edges from calls, catch clauses 404 // can otherwise seem dead. Avoid noting them as dead. 405 count += reachable_code::ScanReachableFromBlock(B, live); 406 continue; 407 } 408 } 409 } 410 411 // Now we know what is live, we check the live precessors of the exit block 412 // and look for fall through paths, being careful to ignore normal returns, 413 // and exceptional paths. 414 bool HasLiveReturn = false; 415 bool HasFakeEdge = false; 416 bool HasPlainEdge = false; 417 bool HasAbnormalEdge = false; 418 419 // Ignore default cases that aren't likely to be reachable because all 420 // enums in a switch(X) have explicit case statements. 421 CFGBlock::FilterOptions FO; 422 FO.IgnoreDefaultsWithCoveredEnums = 1; 423 424 for (CFGBlock::filtered_pred_iterator I = 425 cfg->getExit().filtered_pred_start_end(FO); 426 I.hasMore(); ++I) { 427 const CFGBlock &B = **I; 428 if (!live[B.getBlockID()]) 429 continue; 430 431 // Skip blocks which contain an element marked as no-return. They don't 432 // represent actually viable edges into the exit block, so mark them as 433 // abnormal. 434 if (B.hasNoReturnElement()) { 435 HasAbnormalEdge = true; 436 continue; 437 } 438 439 // Destructors can appear after the 'return' in the CFG. This is 440 // normal. We need to look pass the destructors for the return 441 // statement (if it exists). 442 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend(); 443 444 for ( ; ri != re ; ++ri) 445 if (ri->getAs<CFGStmt>()) 446 break; 447 448 // No more CFGElements in the block? 449 if (ri == re) { 450 const Stmt *Term = B.getTerminatorStmt(); 451 if (Term && isa<CXXTryStmt>(Term)) { 452 HasAbnormalEdge = true; 453 continue; 454 } 455 // A labeled empty statement, or the entry block... 456 HasPlainEdge = true; 457 continue; 458 } 459 460 CFGStmt CS = ri->castAs<CFGStmt>(); 461 const Stmt *S = CS.getStmt(); 462 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) { 463 HasLiveReturn = true; 464 continue; 465 } 466 if (isa<ObjCAtThrowStmt>(S)) { 467 HasFakeEdge = true; 468 continue; 469 } 470 if (isa<CXXThrowExpr>(S)) { 471 HasFakeEdge = true; 472 continue; 473 } 474 if (isa<MSAsmStmt>(S)) { 475 // TODO: Verify this is correct. 476 HasFakeEdge = true; 477 HasLiveReturn = true; 478 continue; 479 } 480 if (isa<CXXTryStmt>(S)) { 481 HasAbnormalEdge = true; 482 continue; 483 } 484 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit()) 485 == B.succ_end()) { 486 HasAbnormalEdge = true; 487 continue; 488 } 489 490 HasPlainEdge = true; 491 } 492 if (!HasPlainEdge) { 493 if (HasLiveReturn) 494 return NeverFallThrough; 495 return NeverFallThroughOrReturn; 496 } 497 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn) 498 return MaybeFallThrough; 499 // This says AlwaysFallThrough for calls to functions that are not marked 500 // noreturn, that don't return. If people would like this warning to be more 501 // accurate, such functions should be marked as noreturn. 502 return AlwaysFallThrough; 503 } 504 505 namespace { 506 507 struct CheckFallThroughDiagnostics { 508 unsigned diag_MaybeFallThrough_HasNoReturn; 509 unsigned diag_MaybeFallThrough_ReturnsNonVoid; 510 unsigned diag_AlwaysFallThrough_HasNoReturn; 511 unsigned diag_AlwaysFallThrough_ReturnsNonVoid; 512 unsigned diag_NeverFallThroughOrReturn; 513 enum { Function, Block, Lambda, Coroutine } funMode; 514 SourceLocation FuncLoc; 515 516 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) { 517 CheckFallThroughDiagnostics D; 518 D.FuncLoc = Func->getLocation(); 519 D.diag_MaybeFallThrough_HasNoReturn = 520 diag::warn_falloff_noreturn_function; 521 D.diag_MaybeFallThrough_ReturnsNonVoid = 522 diag::warn_maybe_falloff_nonvoid_function; 523 D.diag_AlwaysFallThrough_HasNoReturn = 524 diag::warn_falloff_noreturn_function; 525 D.diag_AlwaysFallThrough_ReturnsNonVoid = 526 diag::warn_falloff_nonvoid_function; 527 528 // Don't suggest that virtual functions be marked "noreturn", since they 529 // might be overridden by non-noreturn functions. 530 bool isVirtualMethod = false; 531 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) 532 isVirtualMethod = Method->isVirtual(); 533 534 // Don't suggest that template instantiations be marked "noreturn" 535 bool isTemplateInstantiation = false; 536 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func)) 537 isTemplateInstantiation = Function->isTemplateInstantiation(); 538 539 if (!isVirtualMethod && !isTemplateInstantiation) 540 D.diag_NeverFallThroughOrReturn = 541 diag::warn_suggest_noreturn_function; 542 else 543 D.diag_NeverFallThroughOrReturn = 0; 544 545 D.funMode = Function; 546 return D; 547 } 548 549 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) { 550 CheckFallThroughDiagnostics D; 551 D.FuncLoc = Func->getLocation(); 552 D.diag_MaybeFallThrough_HasNoReturn = 0; 553 D.diag_MaybeFallThrough_ReturnsNonVoid = 554 diag::warn_maybe_falloff_nonvoid_coroutine; 555 D.diag_AlwaysFallThrough_HasNoReturn = 0; 556 D.diag_AlwaysFallThrough_ReturnsNonVoid = 557 diag::warn_falloff_nonvoid_coroutine; 558 D.funMode = Coroutine; 559 return D; 560 } 561 562 static CheckFallThroughDiagnostics MakeForBlock() { 563 CheckFallThroughDiagnostics D; 564 D.diag_MaybeFallThrough_HasNoReturn = 565 diag::err_noreturn_block_has_return_expr; 566 D.diag_MaybeFallThrough_ReturnsNonVoid = 567 diag::err_maybe_falloff_nonvoid_block; 568 D.diag_AlwaysFallThrough_HasNoReturn = 569 diag::err_noreturn_block_has_return_expr; 570 D.diag_AlwaysFallThrough_ReturnsNonVoid = 571 diag::err_falloff_nonvoid_block; 572 D.diag_NeverFallThroughOrReturn = 0; 573 D.funMode = Block; 574 return D; 575 } 576 577 static CheckFallThroughDiagnostics MakeForLambda() { 578 CheckFallThroughDiagnostics D; 579 D.diag_MaybeFallThrough_HasNoReturn = 580 diag::err_noreturn_lambda_has_return_expr; 581 D.diag_MaybeFallThrough_ReturnsNonVoid = 582 diag::warn_maybe_falloff_nonvoid_lambda; 583 D.diag_AlwaysFallThrough_HasNoReturn = 584 diag::err_noreturn_lambda_has_return_expr; 585 D.diag_AlwaysFallThrough_ReturnsNonVoid = 586 diag::warn_falloff_nonvoid_lambda; 587 D.diag_NeverFallThroughOrReturn = 0; 588 D.funMode = Lambda; 589 return D; 590 } 591 592 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid, 593 bool HasNoReturn) const { 594 if (funMode == Function) { 595 return (ReturnsVoid || 596 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, 597 FuncLoc)) && 598 (!HasNoReturn || 599 D.isIgnored(diag::warn_noreturn_function_has_return_expr, 600 FuncLoc)) && 601 (!ReturnsVoid || 602 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc)); 603 } 604 if (funMode == Coroutine) { 605 return (ReturnsVoid || 606 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) || 607 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine, 608 FuncLoc)) && 609 (!HasNoReturn); 610 } 611 // For blocks / lambdas. 612 return ReturnsVoid && !HasNoReturn; 613 } 614 }; 615 616 } // anonymous namespace 617 618 /// CheckFallThroughForBody - Check that we don't fall off the end of a 619 /// function that should return a value. Check that we don't fall off the end 620 /// of a noreturn function. We assume that functions and blocks not marked 621 /// noreturn will return. 622 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, 623 const BlockExpr *blkExpr, 624 const CheckFallThroughDiagnostics &CD, 625 AnalysisDeclContext &AC, 626 sema::FunctionScopeInfo *FSI) { 627 628 bool ReturnsVoid = false; 629 bool HasNoReturn = false; 630 bool IsCoroutine = FSI->isCoroutine(); 631 632 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 633 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body)) 634 ReturnsVoid = CBody->getFallthroughHandler() != nullptr; 635 else 636 ReturnsVoid = FD->getReturnType()->isVoidType(); 637 HasNoReturn = FD->isNoReturn(); 638 } 639 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 640 ReturnsVoid = MD->getReturnType()->isVoidType(); 641 HasNoReturn = MD->hasAttr<NoReturnAttr>(); 642 } 643 else if (isa<BlockDecl>(D)) { 644 QualType BlockTy = blkExpr->getType(); 645 if (const FunctionType *FT = 646 BlockTy->getPointeeType()->getAs<FunctionType>()) { 647 if (FT->getReturnType()->isVoidType()) 648 ReturnsVoid = true; 649 if (FT->getNoReturnAttr()) 650 HasNoReturn = true; 651 } 652 } 653 654 DiagnosticsEngine &Diags = S.getDiagnostics(); 655 656 // Short circuit for compilation speed. 657 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn)) 658 return; 659 SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc(); 660 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) { 661 if (IsCoroutine) 662 S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType(); 663 else 664 S.Diag(Loc, DiagID); 665 }; 666 667 // cpu_dispatch functions permit empty function bodies for ICC compatibility. 668 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion()) 669 return; 670 671 // Either in a function body compound statement, or a function-try-block. 672 switch (CheckFallThrough(AC)) { 673 case UnknownFallThrough: 674 break; 675 676 case MaybeFallThrough: 677 if (HasNoReturn) 678 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn); 679 else if (!ReturnsVoid) 680 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid); 681 break; 682 case AlwaysFallThrough: 683 if (HasNoReturn) 684 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn); 685 else if (!ReturnsVoid) 686 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid); 687 break; 688 case NeverFallThroughOrReturn: 689 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) { 690 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 691 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD; 692 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 693 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD; 694 } else { 695 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn); 696 } 697 } 698 break; 699 case NeverFallThrough: 700 break; 701 } 702 } 703 704 //===----------------------------------------------------------------------===// 705 // -Wuninitialized 706 //===----------------------------------------------------------------------===// 707 708 namespace { 709 /// ContainsReference - A visitor class to search for references to 710 /// a particular declaration (the needle) within any evaluated component of an 711 /// expression (recursively). 712 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> { 713 bool FoundReference; 714 const DeclRefExpr *Needle; 715 716 public: 717 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited; 718 719 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle) 720 : Inherited(Context), FoundReference(false), Needle(Needle) {} 721 722 void VisitExpr(const Expr *E) { 723 // Stop evaluating if we already have a reference. 724 if (FoundReference) 725 return; 726 727 Inherited::VisitExpr(E); 728 } 729 730 void VisitDeclRefExpr(const DeclRefExpr *E) { 731 if (E == Needle) 732 FoundReference = true; 733 else 734 Inherited::VisitDeclRefExpr(E); 735 } 736 737 bool doesContainReference() const { return FoundReference; } 738 }; 739 } // anonymous namespace 740 741 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) { 742 QualType VariableTy = VD->getType().getCanonicalType(); 743 if (VariableTy->isBlockPointerType() && 744 !VD->hasAttr<BlocksAttr>()) { 745 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) 746 << VD->getDeclName() 747 << FixItHint::CreateInsertion(VD->getLocation(), "__block "); 748 return true; 749 } 750 751 // Don't issue a fixit if there is already an initializer. 752 if (VD->getInit()) 753 return false; 754 755 // Don't suggest a fixit inside macros. 756 if (VD->getEndLoc().isMacroID()) 757 return false; 758 759 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); 760 761 // Suggest possible initialization (if any). 762 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); 763 if (Init.empty()) 764 return false; 765 766 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName() 767 << FixItHint::CreateInsertion(Loc, Init); 768 return true; 769 } 770 771 /// Create a fixit to remove an if-like statement, on the assumption that its 772 /// condition is CondVal. 773 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then, 774 const Stmt *Else, bool CondVal, 775 FixItHint &Fixit1, FixItHint &Fixit2) { 776 if (CondVal) { 777 // If condition is always true, remove all but the 'then'. 778 Fixit1 = FixItHint::CreateRemoval( 779 CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc())); 780 if (Else) { 781 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc()); 782 Fixit2 = 783 FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc())); 784 } 785 } else { 786 // If condition is always false, remove all but the 'else'. 787 if (Else) 788 Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange( 789 If->getBeginLoc(), Else->getBeginLoc())); 790 else 791 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange()); 792 } 793 } 794 795 /// DiagUninitUse -- Helper function to produce a diagnostic for an 796 /// uninitialized use of a variable. 797 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use, 798 bool IsCapturedByBlock) { 799 bool Diagnosed = false; 800 801 switch (Use.getKind()) { 802 case UninitUse::Always: 803 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var) 804 << VD->getDeclName() << IsCapturedByBlock 805 << Use.getUser()->getSourceRange(); 806 return; 807 808 case UninitUse::AfterDecl: 809 case UninitUse::AfterCall: 810 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var) 811 << VD->getDeclName() << IsCapturedByBlock 812 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5) 813 << const_cast<DeclContext*>(VD->getLexicalDeclContext()) 814 << VD->getSourceRange(); 815 S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use) 816 << IsCapturedByBlock << Use.getUser()->getSourceRange(); 817 return; 818 819 case UninitUse::Maybe: 820 case UninitUse::Sometimes: 821 // Carry on to report sometimes-uninitialized branches, if possible, 822 // or a 'may be used uninitialized' diagnostic otherwise. 823 break; 824 } 825 826 // Diagnose each branch which leads to a sometimes-uninitialized use. 827 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end(); 828 I != E; ++I) { 829 assert(Use.getKind() == UninitUse::Sometimes); 830 831 const Expr *User = Use.getUser(); 832 const Stmt *Term = I->Terminator; 833 834 // Information used when building the diagnostic. 835 unsigned DiagKind; 836 StringRef Str; 837 SourceRange Range; 838 839 // FixIts to suppress the diagnostic by removing the dead condition. 840 // For all binary terminators, branch 0 is taken if the condition is true, 841 // and branch 1 is taken if the condition is false. 842 int RemoveDiagKind = -1; 843 const char *FixitStr = 844 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false") 845 : (I->Output ? "1" : "0"); 846 FixItHint Fixit1, Fixit2; 847 848 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) { 849 default: 850 // Don't know how to report this. Just fall back to 'may be used 851 // uninitialized'. FIXME: Can this happen? 852 continue; 853 854 // "condition is true / condition is false". 855 case Stmt::IfStmtClass: { 856 const IfStmt *IS = cast<IfStmt>(Term); 857 DiagKind = 0; 858 Str = "if"; 859 Range = IS->getCond()->getSourceRange(); 860 RemoveDiagKind = 0; 861 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(), 862 I->Output, Fixit1, Fixit2); 863 break; 864 } 865 case Stmt::ConditionalOperatorClass: { 866 const ConditionalOperator *CO = cast<ConditionalOperator>(Term); 867 DiagKind = 0; 868 Str = "?:"; 869 Range = CO->getCond()->getSourceRange(); 870 RemoveDiagKind = 0; 871 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(), 872 I->Output, Fixit1, Fixit2); 873 break; 874 } 875 case Stmt::BinaryOperatorClass: { 876 const BinaryOperator *BO = cast<BinaryOperator>(Term); 877 if (!BO->isLogicalOp()) 878 continue; 879 DiagKind = 0; 880 Str = BO->getOpcodeStr(); 881 Range = BO->getLHS()->getSourceRange(); 882 RemoveDiagKind = 0; 883 if ((BO->getOpcode() == BO_LAnd && I->Output) || 884 (BO->getOpcode() == BO_LOr && !I->Output)) 885 // true && y -> y, false || y -> y. 886 Fixit1 = FixItHint::CreateRemoval( 887 SourceRange(BO->getBeginLoc(), BO->getOperatorLoc())); 888 else 889 // false && y -> false, true || y -> true. 890 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr); 891 break; 892 } 893 894 // "loop is entered / loop is exited". 895 case Stmt::WhileStmtClass: 896 DiagKind = 1; 897 Str = "while"; 898 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange(); 899 RemoveDiagKind = 1; 900 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); 901 break; 902 case Stmt::ForStmtClass: 903 DiagKind = 1; 904 Str = "for"; 905 Range = cast<ForStmt>(Term)->getCond()->getSourceRange(); 906 RemoveDiagKind = 1; 907 if (I->Output) 908 Fixit1 = FixItHint::CreateRemoval(Range); 909 else 910 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); 911 break; 912 case Stmt::CXXForRangeStmtClass: 913 if (I->Output == 1) { 914 // The use occurs if a range-based for loop's body never executes. 915 // That may be impossible, and there's no syntactic fix for this, 916 // so treat it as a 'may be uninitialized' case. 917 continue; 918 } 919 DiagKind = 1; 920 Str = "for"; 921 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange(); 922 break; 923 924 // "condition is true / loop is exited". 925 case Stmt::DoStmtClass: 926 DiagKind = 2; 927 Str = "do"; 928 Range = cast<DoStmt>(Term)->getCond()->getSourceRange(); 929 RemoveDiagKind = 1; 930 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); 931 break; 932 933 // "switch case is taken". 934 case Stmt::CaseStmtClass: 935 DiagKind = 3; 936 Str = "case"; 937 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange(); 938 break; 939 case Stmt::DefaultStmtClass: 940 DiagKind = 3; 941 Str = "default"; 942 Range = cast<DefaultStmt>(Term)->getDefaultLoc(); 943 break; 944 } 945 946 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var) 947 << VD->getDeclName() << IsCapturedByBlock << DiagKind 948 << Str << I->Output << Range; 949 S.Diag(User->getBeginLoc(), diag::note_uninit_var_use) 950 << IsCapturedByBlock << User->getSourceRange(); 951 if (RemoveDiagKind != -1) 952 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond) 953 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2; 954 955 Diagnosed = true; 956 } 957 958 if (!Diagnosed) 959 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var) 960 << VD->getDeclName() << IsCapturedByBlock 961 << Use.getUser()->getSourceRange(); 962 } 963 964 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an 965 /// uninitialized variable. This manages the different forms of diagnostic 966 /// emitted for particular types of uses. Returns true if the use was diagnosed 967 /// as a warning. If a particular use is one we omit warnings for, returns 968 /// false. 969 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD, 970 const UninitUse &Use, 971 bool alwaysReportSelfInit = false) { 972 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) { 973 // Inspect the initializer of the variable declaration which is 974 // being referenced prior to its initialization. We emit 975 // specialized diagnostics for self-initialization, and we 976 // specifically avoid warning about self references which take the 977 // form of: 978 // 979 // int x = x; 980 // 981 // This is used to indicate to GCC that 'x' is intentionally left 982 // uninitialized. Proven code paths which access 'x' in 983 // an uninitialized state after this will still warn. 984 if (const Expr *Initializer = VD->getInit()) { 985 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts()) 986 return false; 987 988 ContainsReference CR(S.Context, DRE); 989 CR.Visit(Initializer); 990 if (CR.doesContainReference()) { 991 S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init) 992 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange(); 993 return true; 994 } 995 } 996 997 DiagUninitUse(S, VD, Use, false); 998 } else { 999 const BlockExpr *BE = cast<BlockExpr>(Use.getUser()); 1000 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>()) 1001 S.Diag(BE->getBeginLoc(), 1002 diag::warn_uninit_byref_blockvar_captured_by_block) 1003 << VD->getDeclName() 1004 << VD->getType().getQualifiers().hasObjCLifetime(); 1005 else 1006 DiagUninitUse(S, VD, Use, true); 1007 } 1008 1009 // Report where the variable was declared when the use wasn't within 1010 // the initializer of that declaration & we didn't already suggest 1011 // an initialization fixit. 1012 if (!SuggestInitializationFixit(S, VD)) 1013 S.Diag(VD->getBeginLoc(), diag::note_var_declared_here) 1014 << VD->getDeclName(); 1015 1016 return true; 1017 } 1018 1019 namespace { 1020 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> { 1021 public: 1022 FallthroughMapper(Sema &S) 1023 : FoundSwitchStatements(false), 1024 S(S) { 1025 } 1026 1027 bool foundSwitchStatements() const { return FoundSwitchStatements; } 1028 1029 void markFallthroughVisited(const AttributedStmt *Stmt) { 1030 bool Found = FallthroughStmts.erase(Stmt); 1031 assert(Found); 1032 (void)Found; 1033 } 1034 1035 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts; 1036 1037 const AttrStmts &getFallthroughStmts() const { 1038 return FallthroughStmts; 1039 } 1040 1041 void fillReachableBlocks(CFG *Cfg) { 1042 assert(ReachableBlocks.empty() && "ReachableBlocks already filled"); 1043 std::deque<const CFGBlock *> BlockQueue; 1044 1045 ReachableBlocks.insert(&Cfg->getEntry()); 1046 BlockQueue.push_back(&Cfg->getEntry()); 1047 // Mark all case blocks reachable to avoid problems with switching on 1048 // constants, covered enums, etc. 1049 // These blocks can contain fall-through annotations, and we don't want to 1050 // issue a warn_fallthrough_attr_unreachable for them. 1051 for (const auto *B : *Cfg) { 1052 const Stmt *L = B->getLabel(); 1053 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second) 1054 BlockQueue.push_back(B); 1055 } 1056 1057 while (!BlockQueue.empty()) { 1058 const CFGBlock *P = BlockQueue.front(); 1059 BlockQueue.pop_front(); 1060 for (CFGBlock::const_succ_iterator I = P->succ_begin(), 1061 E = P->succ_end(); 1062 I != E; ++I) { 1063 if (*I && ReachableBlocks.insert(*I).second) 1064 BlockQueue.push_back(*I); 1065 } 1066 } 1067 } 1068 1069 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt, 1070 bool IsTemplateInstantiation) { 1071 assert(!ReachableBlocks.empty() && "ReachableBlocks empty"); 1072 1073 int UnannotatedCnt = 0; 1074 AnnotatedCnt = 0; 1075 1076 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end()); 1077 while (!BlockQueue.empty()) { 1078 const CFGBlock *P = BlockQueue.front(); 1079 BlockQueue.pop_front(); 1080 if (!P) continue; 1081 1082 const Stmt *Term = P->getTerminatorStmt(); 1083 if (Term && isa<SwitchStmt>(Term)) 1084 continue; // Switch statement, good. 1085 1086 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel()); 1087 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end()) 1088 continue; // Previous case label has no statements, good. 1089 1090 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel()); 1091 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end()) 1092 continue; // Case label is preceded with a normal label, good. 1093 1094 if (!ReachableBlocks.count(P)) { 1095 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(), 1096 ElemEnd = P->rend(); 1097 ElemIt != ElemEnd; ++ElemIt) { 1098 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) { 1099 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) { 1100 // Don't issue a warning for an unreachable fallthrough 1101 // attribute in template instantiations as it may not be 1102 // unreachable in all instantiations of the template. 1103 if (!IsTemplateInstantiation) 1104 S.Diag(AS->getBeginLoc(), 1105 diag::warn_fallthrough_attr_unreachable); 1106 markFallthroughVisited(AS); 1107 ++AnnotatedCnt; 1108 break; 1109 } 1110 // Don't care about other unreachable statements. 1111 } 1112 } 1113 // If there are no unreachable statements, this may be a special 1114 // case in CFG: 1115 // case X: { 1116 // A a; // A has a destructor. 1117 // break; 1118 // } 1119 // // <<<< This place is represented by a 'hanging' CFG block. 1120 // case Y: 1121 continue; 1122 } 1123 1124 const Stmt *LastStmt = getLastStmt(*P); 1125 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) { 1126 markFallthroughVisited(AS); 1127 ++AnnotatedCnt; 1128 continue; // Fallthrough annotation, good. 1129 } 1130 1131 if (!LastStmt) { // This block contains no executable statements. 1132 // Traverse its predecessors. 1133 std::copy(P->pred_begin(), P->pred_end(), 1134 std::back_inserter(BlockQueue)); 1135 continue; 1136 } 1137 1138 ++UnannotatedCnt; 1139 } 1140 return !!UnannotatedCnt; 1141 } 1142 1143 // RecursiveASTVisitor setup. 1144 bool shouldWalkTypesOfTypeLocs() const { return false; } 1145 1146 bool VisitAttributedStmt(AttributedStmt *S) { 1147 if (asFallThroughAttr(S)) 1148 FallthroughStmts.insert(S); 1149 return true; 1150 } 1151 1152 bool VisitSwitchStmt(SwitchStmt *S) { 1153 FoundSwitchStatements = true; 1154 return true; 1155 } 1156 1157 // We don't want to traverse local type declarations. We analyze their 1158 // methods separately. 1159 bool TraverseDecl(Decl *D) { return true; } 1160 1161 // We analyze lambda bodies separately. Skip them here. 1162 bool TraverseLambdaExpr(LambdaExpr *LE) { 1163 // Traverse the captures, but not the body. 1164 for (const auto &C : zip(LE->captures(), LE->capture_inits())) 1165 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C)); 1166 return true; 1167 } 1168 1169 private: 1170 1171 static const AttributedStmt *asFallThroughAttr(const Stmt *S) { 1172 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) { 1173 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs())) 1174 return AS; 1175 } 1176 return nullptr; 1177 } 1178 1179 static const Stmt *getLastStmt(const CFGBlock &B) { 1180 if (const Stmt *Term = B.getTerminatorStmt()) 1181 return Term; 1182 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(), 1183 ElemEnd = B.rend(); 1184 ElemIt != ElemEnd; ++ElemIt) { 1185 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) 1186 return CS->getStmt(); 1187 } 1188 // Workaround to detect a statement thrown out by CFGBuilder: 1189 // case X: {} case Y: 1190 // case X: ; case Y: 1191 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel())) 1192 if (!isa<SwitchCase>(SW->getSubStmt())) 1193 return SW->getSubStmt(); 1194 1195 return nullptr; 1196 } 1197 1198 bool FoundSwitchStatements; 1199 AttrStmts FallthroughStmts; 1200 Sema &S; 1201 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks; 1202 }; 1203 } // anonymous namespace 1204 1205 static StringRef getFallthroughAttrSpelling(Preprocessor &PP, 1206 SourceLocation Loc) { 1207 TokenValue FallthroughTokens[] = { 1208 tok::l_square, tok::l_square, 1209 PP.getIdentifierInfo("fallthrough"), 1210 tok::r_square, tok::r_square 1211 }; 1212 1213 TokenValue ClangFallthroughTokens[] = { 1214 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"), 1215 tok::coloncolon, PP.getIdentifierInfo("fallthrough"), 1216 tok::r_square, tok::r_square 1217 }; 1218 1219 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17; 1220 1221 StringRef MacroName; 1222 if (PreferClangAttr) 1223 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens); 1224 if (MacroName.empty()) 1225 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens); 1226 if (MacroName.empty() && !PreferClangAttr) 1227 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens); 1228 if (MacroName.empty()) 1229 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]"; 1230 return MacroName; 1231 } 1232 1233 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC, 1234 bool PerFunction) { 1235 // Only perform this analysis when using [[]] attributes. There is no good 1236 // workflow for this warning when not using C++11. There is no good way to 1237 // silence the warning (no attribute is available) unless we are using 1238 // [[]] attributes. One could use pragmas to silence the warning, but as a 1239 // general solution that is gross and not in the spirit of this warning. 1240 // 1241 // NOTE: This an intermediate solution. There are on-going discussions on 1242 // how to properly support this warning outside of C++11 with an annotation. 1243 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes) 1244 return; 1245 1246 FallthroughMapper FM(S); 1247 FM.TraverseStmt(AC.getBody()); 1248 1249 if (!FM.foundSwitchStatements()) 1250 return; 1251 1252 if (PerFunction && FM.getFallthroughStmts().empty()) 1253 return; 1254 1255 CFG *Cfg = AC.getCFG(); 1256 1257 if (!Cfg) 1258 return; 1259 1260 FM.fillReachableBlocks(Cfg); 1261 1262 for (const CFGBlock *B : llvm::reverse(*Cfg)) { 1263 const Stmt *Label = B->getLabel(); 1264 1265 if (!Label || !isa<SwitchCase>(Label)) 1266 continue; 1267 1268 int AnnotatedCnt; 1269 1270 bool IsTemplateInstantiation = false; 1271 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl())) 1272 IsTemplateInstantiation = Function->isTemplateInstantiation(); 1273 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt, 1274 IsTemplateInstantiation)) 1275 continue; 1276 1277 S.Diag(Label->getBeginLoc(), 1278 PerFunction ? diag::warn_unannotated_fallthrough_per_function 1279 : diag::warn_unannotated_fallthrough); 1280 1281 if (!AnnotatedCnt) { 1282 SourceLocation L = Label->getBeginLoc(); 1283 if (L.isMacroID()) 1284 continue; 1285 if (S.getLangOpts().CPlusPlus11) { 1286 const Stmt *Term = B->getTerminatorStmt(); 1287 // Skip empty cases. 1288 while (B->empty() && !Term && B->succ_size() == 1) { 1289 B = *B->succ_begin(); 1290 Term = B->getTerminatorStmt(); 1291 } 1292 if (!(B->empty() && Term && isa<BreakStmt>(Term))) { 1293 Preprocessor &PP = S.getPreprocessor(); 1294 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L); 1295 SmallString<64> TextToInsert(AnnotationSpelling); 1296 TextToInsert += "; "; 1297 S.Diag(L, diag::note_insert_fallthrough_fixit) << 1298 AnnotationSpelling << 1299 FixItHint::CreateInsertion(L, TextToInsert); 1300 } 1301 } 1302 S.Diag(L, diag::note_insert_break_fixit) << 1303 FixItHint::CreateInsertion(L, "break; "); 1304 } 1305 } 1306 1307 for (const auto *F : FM.getFallthroughStmts()) 1308 S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement); 1309 } 1310 1311 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM, 1312 const Stmt *S) { 1313 assert(S); 1314 1315 do { 1316 switch (S->getStmtClass()) { 1317 case Stmt::ForStmtClass: 1318 case Stmt::WhileStmtClass: 1319 case Stmt::CXXForRangeStmtClass: 1320 case Stmt::ObjCForCollectionStmtClass: 1321 return true; 1322 case Stmt::DoStmtClass: { 1323 Expr::EvalResult Result; 1324 if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx)) 1325 return true; 1326 return Result.Val.getInt().getBoolValue(); 1327 } 1328 default: 1329 break; 1330 } 1331 } while ((S = PM.getParent(S))); 1332 1333 return false; 1334 } 1335 1336 static void diagnoseRepeatedUseOfWeak(Sema &S, 1337 const sema::FunctionScopeInfo *CurFn, 1338 const Decl *D, 1339 const ParentMap &PM) { 1340 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy; 1341 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap; 1342 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector; 1343 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator> 1344 StmtUsesPair; 1345 1346 ASTContext &Ctx = S.getASTContext(); 1347 1348 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses(); 1349 1350 // Extract all weak objects that are referenced more than once. 1351 SmallVector<StmtUsesPair, 8> UsesByStmt; 1352 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end(); 1353 I != E; ++I) { 1354 const WeakUseVector &Uses = I->second; 1355 1356 // Find the first read of the weak object. 1357 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end(); 1358 for ( ; UI != UE; ++UI) { 1359 if (UI->isUnsafe()) 1360 break; 1361 } 1362 1363 // If there were only writes to this object, don't warn. 1364 if (UI == UE) 1365 continue; 1366 1367 // If there was only one read, followed by any number of writes, and the 1368 // read is not within a loop, don't warn. Additionally, don't warn in a 1369 // loop if the base object is a local variable -- local variables are often 1370 // changed in loops. 1371 if (UI == Uses.begin()) { 1372 WeakUseVector::const_iterator UI2 = UI; 1373 for (++UI2; UI2 != UE; ++UI2) 1374 if (UI2->isUnsafe()) 1375 break; 1376 1377 if (UI2 == UE) { 1378 if (!isInLoop(Ctx, PM, UI->getUseExpr())) 1379 continue; 1380 1381 const WeakObjectProfileTy &Profile = I->first; 1382 if (!Profile.isExactProfile()) 1383 continue; 1384 1385 const NamedDecl *Base = Profile.getBase(); 1386 if (!Base) 1387 Base = Profile.getProperty(); 1388 assert(Base && "A profile always has a base or property."); 1389 1390 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base)) 1391 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base)) 1392 continue; 1393 } 1394 } 1395 1396 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I)); 1397 } 1398 1399 if (UsesByStmt.empty()) 1400 return; 1401 1402 // Sort by first use so that we emit the warnings in a deterministic order. 1403 SourceManager &SM = S.getSourceManager(); 1404 llvm::sort(UsesByStmt, 1405 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) { 1406 return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(), 1407 RHS.first->getBeginLoc()); 1408 }); 1409 1410 // Classify the current code body for better warning text. 1411 // This enum should stay in sync with the cases in 1412 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak. 1413 // FIXME: Should we use a common classification enum and the same set of 1414 // possibilities all throughout Sema? 1415 enum { 1416 Function, 1417 Method, 1418 Block, 1419 Lambda 1420 } FunctionKind; 1421 1422 if (isa<sema::BlockScopeInfo>(CurFn)) 1423 FunctionKind = Block; 1424 else if (isa<sema::LambdaScopeInfo>(CurFn)) 1425 FunctionKind = Lambda; 1426 else if (isa<ObjCMethodDecl>(D)) 1427 FunctionKind = Method; 1428 else 1429 FunctionKind = Function; 1430 1431 // Iterate through the sorted problems and emit warnings for each. 1432 for (const auto &P : UsesByStmt) { 1433 const Stmt *FirstRead = P.first; 1434 const WeakObjectProfileTy &Key = P.second->first; 1435 const WeakUseVector &Uses = P.second->second; 1436 1437 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy 1438 // may not contain enough information to determine that these are different 1439 // properties. We can only be 100% sure of a repeated use in certain cases, 1440 // and we adjust the diagnostic kind accordingly so that the less certain 1441 // case can be turned off if it is too noisy. 1442 unsigned DiagKind; 1443 if (Key.isExactProfile()) 1444 DiagKind = diag::warn_arc_repeated_use_of_weak; 1445 else 1446 DiagKind = diag::warn_arc_possible_repeated_use_of_weak; 1447 1448 // Classify the weak object being accessed for better warning text. 1449 // This enum should stay in sync with the cases in 1450 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak. 1451 enum { 1452 Variable, 1453 Property, 1454 ImplicitProperty, 1455 Ivar 1456 } ObjectKind; 1457 1458 const NamedDecl *KeyProp = Key.getProperty(); 1459 if (isa<VarDecl>(KeyProp)) 1460 ObjectKind = Variable; 1461 else if (isa<ObjCPropertyDecl>(KeyProp)) 1462 ObjectKind = Property; 1463 else if (isa<ObjCMethodDecl>(KeyProp)) 1464 ObjectKind = ImplicitProperty; 1465 else if (isa<ObjCIvarDecl>(KeyProp)) 1466 ObjectKind = Ivar; 1467 else 1468 llvm_unreachable("Unexpected weak object kind!"); 1469 1470 // Do not warn about IBOutlet weak property receivers being set to null 1471 // since they are typically only used from the main thread. 1472 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp)) 1473 if (Prop->hasAttr<IBOutletAttr>()) 1474 continue; 1475 1476 // Show the first time the object was read. 1477 S.Diag(FirstRead->getBeginLoc(), DiagKind) 1478 << int(ObjectKind) << KeyProp << int(FunctionKind) 1479 << FirstRead->getSourceRange(); 1480 1481 // Print all the other accesses as notes. 1482 for (const auto &Use : Uses) { 1483 if (Use.getUseExpr() == FirstRead) 1484 continue; 1485 S.Diag(Use.getUseExpr()->getBeginLoc(), 1486 diag::note_arc_weak_also_accessed_here) 1487 << Use.getUseExpr()->getSourceRange(); 1488 } 1489 } 1490 } 1491 1492 namespace { 1493 class UninitValsDiagReporter : public UninitVariablesHandler { 1494 Sema &S; 1495 typedef SmallVector<UninitUse, 2> UsesVec; 1496 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType; 1497 // Prefer using MapVector to DenseMap, so that iteration order will be 1498 // the same as insertion order. This is needed to obtain a deterministic 1499 // order of diagnostics when calling flushDiagnostics(). 1500 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap; 1501 UsesMap uses; 1502 1503 public: 1504 UninitValsDiagReporter(Sema &S) : S(S) {} 1505 ~UninitValsDiagReporter() override { flushDiagnostics(); } 1506 1507 MappedType &getUses(const VarDecl *vd) { 1508 MappedType &V = uses[vd]; 1509 if (!V.getPointer()) 1510 V.setPointer(new UsesVec()); 1511 return V; 1512 } 1513 1514 void handleUseOfUninitVariable(const VarDecl *vd, 1515 const UninitUse &use) override { 1516 getUses(vd).getPointer()->push_back(use); 1517 } 1518 1519 void handleSelfInit(const VarDecl *vd) override { 1520 getUses(vd).setInt(true); 1521 } 1522 1523 void flushDiagnostics() { 1524 for (const auto &P : uses) { 1525 const VarDecl *vd = P.first; 1526 const MappedType &V = P.second; 1527 1528 UsesVec *vec = V.getPointer(); 1529 bool hasSelfInit = V.getInt(); 1530 1531 // Specially handle the case where we have uses of an uninitialized 1532 // variable, but the root cause is an idiomatic self-init. We want 1533 // to report the diagnostic at the self-init since that is the root cause. 1534 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec)) 1535 DiagnoseUninitializedUse(S, vd, 1536 UninitUse(vd->getInit()->IgnoreParenCasts(), 1537 /* isAlwaysUninit */ true), 1538 /* alwaysReportSelfInit */ true); 1539 else { 1540 // Sort the uses by their SourceLocations. While not strictly 1541 // guaranteed to produce them in line/column order, this will provide 1542 // a stable ordering. 1543 llvm::sort(vec->begin(), vec->end(), 1544 [](const UninitUse &a, const UninitUse &b) { 1545 // Prefer a more confident report over a less confident one. 1546 if (a.getKind() != b.getKind()) 1547 return a.getKind() > b.getKind(); 1548 return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc(); 1549 }); 1550 1551 for (const auto &U : *vec) { 1552 // If we have self-init, downgrade all uses to 'may be uninitialized'. 1553 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U; 1554 1555 if (DiagnoseUninitializedUse(S, vd, Use)) 1556 // Skip further diagnostics for this variable. We try to warn only 1557 // on the first point at which a variable is used uninitialized. 1558 break; 1559 } 1560 } 1561 1562 // Release the uses vector. 1563 delete vec; 1564 } 1565 1566 uses.clear(); 1567 } 1568 1569 private: 1570 static bool hasAlwaysUninitializedUse(const UsesVec* vec) { 1571 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) { 1572 return U.getKind() == UninitUse::Always || 1573 U.getKind() == UninitUse::AfterCall || 1574 U.getKind() == UninitUse::AfterDecl; 1575 }); 1576 } 1577 }; 1578 } // anonymous namespace 1579 1580 namespace clang { 1581 namespace { 1582 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes; 1583 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag; 1584 typedef std::list<DelayedDiag> DiagList; 1585 1586 struct SortDiagBySourceLocation { 1587 SourceManager &SM; 1588 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {} 1589 1590 bool operator()(const DelayedDiag &left, const DelayedDiag &right) { 1591 // Although this call will be slow, this is only called when outputting 1592 // multiple warnings. 1593 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first); 1594 } 1595 }; 1596 } // anonymous namespace 1597 } // namespace clang 1598 1599 //===----------------------------------------------------------------------===// 1600 // -Wthread-safety 1601 //===----------------------------------------------------------------------===// 1602 namespace clang { 1603 namespace threadSafety { 1604 namespace { 1605 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler { 1606 Sema &S; 1607 DiagList Warnings; 1608 SourceLocation FunLocation, FunEndLocation; 1609 1610 const FunctionDecl *CurrentFunction; 1611 bool Verbose; 1612 1613 OptionalNotes getNotes() const { 1614 if (Verbose && CurrentFunction) { 1615 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), 1616 S.PDiag(diag::note_thread_warning_in_fun) 1617 << CurrentFunction); 1618 return OptionalNotes(1, FNote); 1619 } 1620 return OptionalNotes(); 1621 } 1622 1623 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const { 1624 OptionalNotes ONS(1, Note); 1625 if (Verbose && CurrentFunction) { 1626 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), 1627 S.PDiag(diag::note_thread_warning_in_fun) 1628 << CurrentFunction); 1629 ONS.push_back(std::move(FNote)); 1630 } 1631 return ONS; 1632 } 1633 1634 OptionalNotes getNotes(const PartialDiagnosticAt &Note1, 1635 const PartialDiagnosticAt &Note2) const { 1636 OptionalNotes ONS; 1637 ONS.push_back(Note1); 1638 ONS.push_back(Note2); 1639 if (Verbose && CurrentFunction) { 1640 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), 1641 S.PDiag(diag::note_thread_warning_in_fun) 1642 << CurrentFunction); 1643 ONS.push_back(std::move(FNote)); 1644 } 1645 return ONS; 1646 } 1647 1648 OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) { 1649 return LocLocked.isValid() 1650 ? getNotes(PartialDiagnosticAt( 1651 LocLocked, S.PDiag(diag::note_locked_here) << Kind)) 1652 : getNotes(); 1653 } 1654 1655 public: 1656 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL) 1657 : S(S), FunLocation(FL), FunEndLocation(FEL), 1658 CurrentFunction(nullptr), Verbose(false) {} 1659 1660 void setVerbose(bool b) { Verbose = b; } 1661 1662 /// Emit all buffered diagnostics in order of sourcelocation. 1663 /// We need to output diagnostics produced while iterating through 1664 /// the lockset in deterministic order, so this function orders diagnostics 1665 /// and outputs them. 1666 void emitDiagnostics() { 1667 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager())); 1668 for (const auto &Diag : Warnings) { 1669 S.Diag(Diag.first.first, Diag.first.second); 1670 for (const auto &Note : Diag.second) 1671 S.Diag(Note.first, Note.second); 1672 } 1673 } 1674 1675 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override { 1676 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock) 1677 << Loc); 1678 Warnings.emplace_back(std::move(Warning), getNotes()); 1679 } 1680 1681 void handleUnmatchedUnlock(StringRef Kind, Name LockName, 1682 SourceLocation Loc) override { 1683 if (Loc.isInvalid()) 1684 Loc = FunLocation; 1685 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_but_no_lock) 1686 << Kind << LockName); 1687 Warnings.emplace_back(std::move(Warning), getNotes()); 1688 } 1689 1690 void handleIncorrectUnlockKind(StringRef Kind, Name LockName, 1691 LockKind Expected, LockKind Received, 1692 SourceLocation LocLocked, 1693 SourceLocation LocUnlock) override { 1694 if (LocUnlock.isInvalid()) 1695 LocUnlock = FunLocation; 1696 PartialDiagnosticAt Warning( 1697 LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch) 1698 << Kind << LockName << Received << Expected); 1699 Warnings.emplace_back(std::move(Warning), 1700 makeLockedHereNote(LocLocked, Kind)); 1701 } 1702 1703 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked, 1704 SourceLocation LocDoubleLock) override { 1705 if (LocDoubleLock.isInvalid()) 1706 LocDoubleLock = FunLocation; 1707 PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(diag::warn_double_lock) 1708 << Kind << LockName); 1709 Warnings.emplace_back(std::move(Warning), 1710 makeLockedHereNote(LocLocked, Kind)); 1711 } 1712 1713 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName, 1714 SourceLocation LocLocked, 1715 SourceLocation LocEndOfScope, 1716 LockErrorKind LEK) override { 1717 unsigned DiagID = 0; 1718 switch (LEK) { 1719 case LEK_LockedSomePredecessors: 1720 DiagID = diag::warn_lock_some_predecessors; 1721 break; 1722 case LEK_LockedSomeLoopIterations: 1723 DiagID = diag::warn_expecting_lock_held_on_loop; 1724 break; 1725 case LEK_LockedAtEndOfFunction: 1726 DiagID = diag::warn_no_unlock; 1727 break; 1728 case LEK_NotLockedAtEndOfFunction: 1729 DiagID = diag::warn_expecting_locked; 1730 break; 1731 } 1732 if (LocEndOfScope.isInvalid()) 1733 LocEndOfScope = FunEndLocation; 1734 1735 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind 1736 << LockName); 1737 Warnings.emplace_back(std::move(Warning), 1738 makeLockedHereNote(LocLocked, Kind)); 1739 } 1740 1741 void handleExclusiveAndShared(StringRef Kind, Name LockName, 1742 SourceLocation Loc1, 1743 SourceLocation Loc2) override { 1744 PartialDiagnosticAt Warning(Loc1, 1745 S.PDiag(diag::warn_lock_exclusive_and_shared) 1746 << Kind << LockName); 1747 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) 1748 << Kind << LockName); 1749 Warnings.emplace_back(std::move(Warning), getNotes(Note)); 1750 } 1751 1752 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D, 1753 ProtectedOperationKind POK, AccessKind AK, 1754 SourceLocation Loc) override { 1755 assert((POK == POK_VarAccess || POK == POK_VarDereference) && 1756 "Only works for variables"); 1757 unsigned DiagID = POK == POK_VarAccess? 1758 diag::warn_variable_requires_any_lock: 1759 diag::warn_var_deref_requires_any_lock; 1760 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) 1761 << D << getLockKindFromAccessKind(AK)); 1762 Warnings.emplace_back(std::move(Warning), getNotes()); 1763 } 1764 1765 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D, 1766 ProtectedOperationKind POK, Name LockName, 1767 LockKind LK, SourceLocation Loc, 1768 Name *PossibleMatch) override { 1769 unsigned DiagID = 0; 1770 if (PossibleMatch) { 1771 switch (POK) { 1772 case POK_VarAccess: 1773 DiagID = diag::warn_variable_requires_lock_precise; 1774 break; 1775 case POK_VarDereference: 1776 DiagID = diag::warn_var_deref_requires_lock_precise; 1777 break; 1778 case POK_FunctionCall: 1779 DiagID = diag::warn_fun_requires_lock_precise; 1780 break; 1781 case POK_PassByRef: 1782 DiagID = diag::warn_guarded_pass_by_reference; 1783 break; 1784 case POK_PtPassByRef: 1785 DiagID = diag::warn_pt_guarded_pass_by_reference; 1786 break; 1787 } 1788 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind 1789 << D 1790 << LockName << LK); 1791 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match) 1792 << *PossibleMatch); 1793 if (Verbose && POK == POK_VarAccess) { 1794 PartialDiagnosticAt VNote(D->getLocation(), 1795 S.PDiag(diag::note_guarded_by_declared_here) 1796 << D->getNameAsString()); 1797 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote)); 1798 } else 1799 Warnings.emplace_back(std::move(Warning), getNotes(Note)); 1800 } else { 1801 switch (POK) { 1802 case POK_VarAccess: 1803 DiagID = diag::warn_variable_requires_lock; 1804 break; 1805 case POK_VarDereference: 1806 DiagID = diag::warn_var_deref_requires_lock; 1807 break; 1808 case POK_FunctionCall: 1809 DiagID = diag::warn_fun_requires_lock; 1810 break; 1811 case POK_PassByRef: 1812 DiagID = diag::warn_guarded_pass_by_reference; 1813 break; 1814 case POK_PtPassByRef: 1815 DiagID = diag::warn_pt_guarded_pass_by_reference; 1816 break; 1817 } 1818 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind 1819 << D 1820 << LockName << LK); 1821 if (Verbose && POK == POK_VarAccess) { 1822 PartialDiagnosticAt Note(D->getLocation(), 1823 S.PDiag(diag::note_guarded_by_declared_here)); 1824 Warnings.emplace_back(std::move(Warning), getNotes(Note)); 1825 } else 1826 Warnings.emplace_back(std::move(Warning), getNotes()); 1827 } 1828 } 1829 1830 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg, 1831 SourceLocation Loc) override { 1832 PartialDiagnosticAt Warning(Loc, 1833 S.PDiag(diag::warn_acquire_requires_negative_cap) 1834 << Kind << LockName << Neg); 1835 Warnings.emplace_back(std::move(Warning), getNotes()); 1836 } 1837 1838 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName, 1839 SourceLocation Loc) override { 1840 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex) 1841 << Kind << FunName << LockName); 1842 Warnings.emplace_back(std::move(Warning), getNotes()); 1843 } 1844 1845 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name, 1846 SourceLocation Loc) override { 1847 PartialDiagnosticAt Warning(Loc, 1848 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name); 1849 Warnings.emplace_back(std::move(Warning), getNotes()); 1850 } 1851 1852 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override { 1853 PartialDiagnosticAt Warning(Loc, 1854 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name); 1855 Warnings.emplace_back(std::move(Warning), getNotes()); 1856 } 1857 1858 void enterFunction(const FunctionDecl* FD) override { 1859 CurrentFunction = FD; 1860 } 1861 1862 void leaveFunction(const FunctionDecl* FD) override { 1863 CurrentFunction = nullptr; 1864 } 1865 }; 1866 } // anonymous namespace 1867 } // namespace threadSafety 1868 } // namespace clang 1869 1870 //===----------------------------------------------------------------------===// 1871 // -Wconsumed 1872 //===----------------------------------------------------------------------===// 1873 1874 namespace clang { 1875 namespace consumed { 1876 namespace { 1877 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase { 1878 1879 Sema &S; 1880 DiagList Warnings; 1881 1882 public: 1883 1884 ConsumedWarningsHandler(Sema &S) : S(S) {} 1885 1886 void emitDiagnostics() override { 1887 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager())); 1888 for (const auto &Diag : Warnings) { 1889 S.Diag(Diag.first.first, Diag.first.second); 1890 for (const auto &Note : Diag.second) 1891 S.Diag(Note.first, Note.second); 1892 } 1893 } 1894 1895 void warnLoopStateMismatch(SourceLocation Loc, 1896 StringRef VariableName) override { 1897 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) << 1898 VariableName); 1899 1900 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 1901 } 1902 1903 void warnParamReturnTypestateMismatch(SourceLocation Loc, 1904 StringRef VariableName, 1905 StringRef ExpectedState, 1906 StringRef ObservedState) override { 1907 1908 PartialDiagnosticAt Warning(Loc, S.PDiag( 1909 diag::warn_param_return_typestate_mismatch) << VariableName << 1910 ExpectedState << ObservedState); 1911 1912 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 1913 } 1914 1915 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, 1916 StringRef ObservedState) override { 1917 1918 PartialDiagnosticAt Warning(Loc, S.PDiag( 1919 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState); 1920 1921 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 1922 } 1923 1924 void warnReturnTypestateForUnconsumableType(SourceLocation Loc, 1925 StringRef TypeName) override { 1926 PartialDiagnosticAt Warning(Loc, S.PDiag( 1927 diag::warn_return_typestate_for_unconsumable_type) << TypeName); 1928 1929 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 1930 } 1931 1932 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, 1933 StringRef ObservedState) override { 1934 1935 PartialDiagnosticAt Warning(Loc, S.PDiag( 1936 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState); 1937 1938 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 1939 } 1940 1941 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State, 1942 SourceLocation Loc) override { 1943 1944 PartialDiagnosticAt Warning(Loc, S.PDiag( 1945 diag::warn_use_of_temp_in_invalid_state) << MethodName << State); 1946 1947 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 1948 } 1949 1950 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName, 1951 StringRef State, SourceLocation Loc) override { 1952 1953 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) << 1954 MethodName << VariableName << State); 1955 1956 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 1957 } 1958 }; 1959 } // anonymous namespace 1960 } // namespace consumed 1961 } // namespace clang 1962 1963 //===----------------------------------------------------------------------===// 1964 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based 1965 // warnings on a function, method, or block. 1966 //===----------------------------------------------------------------------===// 1967 1968 clang::sema::AnalysisBasedWarnings::Policy::Policy() { 1969 enableCheckFallThrough = 1; 1970 enableCheckUnreachable = 0; 1971 enableThreadSafetyAnalysis = 0; 1972 enableConsumedAnalysis = 0; 1973 } 1974 1975 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) { 1976 return (unsigned)!D.isIgnored(diag, SourceLocation()); 1977 } 1978 1979 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) 1980 : S(s), 1981 NumFunctionsAnalyzed(0), 1982 NumFunctionsWithBadCFGs(0), 1983 NumCFGBlocks(0), 1984 MaxCFGBlocksPerFunction(0), 1985 NumUninitAnalysisFunctions(0), 1986 NumUninitAnalysisVariables(0), 1987 MaxUninitAnalysisVariablesPerFunction(0), 1988 NumUninitAnalysisBlockVisits(0), 1989 MaxUninitAnalysisBlockVisitsPerFunction(0) { 1990 1991 using namespace diag; 1992 DiagnosticsEngine &D = S.getDiagnostics(); 1993 1994 DefaultPolicy.enableCheckUnreachable = 1995 isEnabled(D, warn_unreachable) || 1996 isEnabled(D, warn_unreachable_break) || 1997 isEnabled(D, warn_unreachable_return) || 1998 isEnabled(D, warn_unreachable_loop_increment); 1999 2000 DefaultPolicy.enableThreadSafetyAnalysis = 2001 isEnabled(D, warn_double_lock); 2002 2003 DefaultPolicy.enableConsumedAnalysis = 2004 isEnabled(D, warn_use_in_invalid_state); 2005 } 2006 2007 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) { 2008 for (const auto &D : fscope->PossiblyUnreachableDiags) 2009 S.Diag(D.Loc, D.PD); 2010 } 2011 2012 void clang::sema:: 2013 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, 2014 sema::FunctionScopeInfo *fscope, 2015 const Decl *D, const BlockExpr *blkExpr) { 2016 2017 // We avoid doing analysis-based warnings when there are errors for 2018 // two reasons: 2019 // (1) The CFGs often can't be constructed (if the body is invalid), so 2020 // don't bother trying. 2021 // (2) The code already has problems; running the analysis just takes more 2022 // time. 2023 DiagnosticsEngine &Diags = S.getDiagnostics(); 2024 2025 // Do not do any analysis if we are going to just ignore them. 2026 if (Diags.getIgnoreAllWarnings() || 2027 (Diags.getSuppressSystemWarnings() && 2028 S.SourceMgr.isInSystemHeader(D->getLocation()))) 2029 return; 2030 2031 // For code in dependent contexts, we'll do this at instantiation time. 2032 if (cast<DeclContext>(D)->isDependentContext()) 2033 return; 2034 2035 if (Diags.hasUncompilableErrorOccurred()) { 2036 // Flush out any possibly unreachable diagnostics. 2037 flushDiagnostics(S, fscope); 2038 return; 2039 } 2040 2041 const Stmt *Body = D->getBody(); 2042 assert(Body); 2043 2044 // Construct the analysis context with the specified CFG build options. 2045 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D); 2046 2047 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2 2048 // explosion for destructors that can result and the compile time hit. 2049 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true; 2050 AC.getCFGBuildOptions().AddEHEdges = false; 2051 AC.getCFGBuildOptions().AddInitializers = true; 2052 AC.getCFGBuildOptions().AddImplicitDtors = true; 2053 AC.getCFGBuildOptions().AddTemporaryDtors = true; 2054 AC.getCFGBuildOptions().AddCXXNewAllocator = false; 2055 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true; 2056 2057 // Force that certain expressions appear as CFGElements in the CFG. This 2058 // is used to speed up various analyses. 2059 // FIXME: This isn't the right factoring. This is here for initial 2060 // prototyping, but we need a way for analyses to say what expressions they 2061 // expect to always be CFGElements and then fill in the BuildOptions 2062 // appropriately. This is essentially a layering violation. 2063 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis || 2064 P.enableConsumedAnalysis) { 2065 // Unreachable code analysis and thread safety require a linearized CFG. 2066 AC.getCFGBuildOptions().setAllAlwaysAdd(); 2067 } 2068 else { 2069 AC.getCFGBuildOptions() 2070 .setAlwaysAdd(Stmt::BinaryOperatorClass) 2071 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass) 2072 .setAlwaysAdd(Stmt::BlockExprClass) 2073 .setAlwaysAdd(Stmt::CStyleCastExprClass) 2074 .setAlwaysAdd(Stmt::DeclRefExprClass) 2075 .setAlwaysAdd(Stmt::ImplicitCastExprClass) 2076 .setAlwaysAdd(Stmt::UnaryOperatorClass) 2077 .setAlwaysAdd(Stmt::AttributedStmtClass); 2078 } 2079 2080 // Install the logical handler for -Wtautological-overlap-compare 2081 llvm::Optional<LogicalErrorHandler> LEH; 2082 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison, 2083 D->getBeginLoc())) { 2084 LEH.emplace(S); 2085 AC.getCFGBuildOptions().Observer = &*LEH; 2086 } 2087 2088 // Emit delayed diagnostics. 2089 if (!fscope->PossiblyUnreachableDiags.empty()) { 2090 bool analyzed = false; 2091 2092 // Register the expressions with the CFGBuilder. 2093 for (const auto &D : fscope->PossiblyUnreachableDiags) { 2094 for (const Stmt *S : D.Stmts) 2095 AC.registerForcedBlockExpression(S); 2096 } 2097 2098 if (AC.getCFG()) { 2099 analyzed = true; 2100 for (const auto &D : fscope->PossiblyUnreachableDiags) { 2101 bool AllReachable = true; 2102 for (const Stmt *S : D.Stmts) { 2103 const CFGBlock *block = AC.getBlockForRegisteredExpression(S); 2104 CFGReverseBlockReachabilityAnalysis *cra = 2105 AC.getCFGReachablityAnalysis(); 2106 // FIXME: We should be able to assert that block is non-null, but 2107 // the CFG analysis can skip potentially-evaluated expressions in 2108 // edge cases; see test/Sema/vla-2.c. 2109 if (block && cra) { 2110 // Can this block be reached from the entrance? 2111 if (!cra->isReachable(&AC.getCFG()->getEntry(), block)) { 2112 AllReachable = false; 2113 break; 2114 } 2115 } 2116 // If we cannot map to a basic block, assume the statement is 2117 // reachable. 2118 } 2119 2120 if (AllReachable) 2121 S.Diag(D.Loc, D.PD); 2122 } 2123 } 2124 2125 if (!analyzed) 2126 flushDiagnostics(S, fscope); 2127 } 2128 2129 // Warning: check missing 'return' 2130 if (P.enableCheckFallThrough) { 2131 const CheckFallThroughDiagnostics &CD = 2132 (isa<BlockDecl>(D) 2133 ? CheckFallThroughDiagnostics::MakeForBlock() 2134 : (isa<CXXMethodDecl>(D) && 2135 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call && 2136 cast<CXXMethodDecl>(D)->getParent()->isLambda()) 2137 ? CheckFallThroughDiagnostics::MakeForLambda() 2138 : (fscope->isCoroutine() 2139 ? CheckFallThroughDiagnostics::MakeForCoroutine(D) 2140 : CheckFallThroughDiagnostics::MakeForFunction(D))); 2141 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope); 2142 } 2143 2144 // Warning: check for unreachable code 2145 if (P.enableCheckUnreachable) { 2146 // Only check for unreachable code on non-template instantiations. 2147 // Different template instantiations can effectively change the control-flow 2148 // and it is very difficult to prove that a snippet of code in a template 2149 // is unreachable for all instantiations. 2150 bool isTemplateInstantiation = false; 2151 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 2152 isTemplateInstantiation = Function->isTemplateInstantiation(); 2153 if (!isTemplateInstantiation) 2154 CheckUnreachable(S, AC); 2155 } 2156 2157 // Check for thread safety violations 2158 if (P.enableThreadSafetyAnalysis) { 2159 SourceLocation FL = AC.getDecl()->getLocation(); 2160 SourceLocation FEL = AC.getDecl()->getEndLoc(); 2161 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL); 2162 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc())) 2163 Reporter.setIssueBetaWarnings(true); 2164 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc())) 2165 Reporter.setVerbose(true); 2166 2167 threadSafety::runThreadSafetyAnalysis(AC, Reporter, 2168 &S.ThreadSafetyDeclCache); 2169 Reporter.emitDiagnostics(); 2170 } 2171 2172 // Check for violations of consumed properties. 2173 if (P.enableConsumedAnalysis) { 2174 consumed::ConsumedWarningsHandler WarningHandler(S); 2175 consumed::ConsumedAnalyzer Analyzer(WarningHandler); 2176 Analyzer.run(AC); 2177 } 2178 2179 if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) || 2180 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) || 2181 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())) { 2182 if (CFG *cfg = AC.getCFG()) { 2183 UninitValsDiagReporter reporter(S); 2184 UninitVariablesAnalysisStats stats; 2185 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats)); 2186 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC, 2187 reporter, stats); 2188 2189 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) { 2190 ++NumUninitAnalysisFunctions; 2191 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed; 2192 NumUninitAnalysisBlockVisits += stats.NumBlockVisits; 2193 MaxUninitAnalysisVariablesPerFunction = 2194 std::max(MaxUninitAnalysisVariablesPerFunction, 2195 stats.NumVariablesAnalyzed); 2196 MaxUninitAnalysisBlockVisitsPerFunction = 2197 std::max(MaxUninitAnalysisBlockVisitsPerFunction, 2198 stats.NumBlockVisits); 2199 } 2200 } 2201 } 2202 2203 bool FallThroughDiagFull = 2204 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc()); 2205 bool FallThroughDiagPerFunction = !Diags.isIgnored( 2206 diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc()); 2207 if (FallThroughDiagFull || FallThroughDiagPerFunction || 2208 fscope->HasFallthroughStmt) { 2209 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull); 2210 } 2211 2212 if (S.getLangOpts().ObjCWeak && 2213 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc())) 2214 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap()); 2215 2216 2217 // Check for infinite self-recursion in functions 2218 if (!Diags.isIgnored(diag::warn_infinite_recursive_function, 2219 D->getBeginLoc())) { 2220 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2221 checkRecursiveFunction(S, FD, Body, AC); 2222 } 2223 } 2224 2225 // Check for throw out of non-throwing function. 2226 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc())) 2227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2228 if (S.getLangOpts().CPlusPlus && isNoexcept(FD)) 2229 checkThrowInNonThrowingFunc(S, FD, AC); 2230 2231 // If none of the previous checks caused a CFG build, trigger one here 2232 // for -Wtautological-overlap-compare 2233 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison, 2234 D->getBeginLoc())) { 2235 AC.getCFG(); 2236 } 2237 2238 // Collect statistics about the CFG if it was built. 2239 if (S.CollectStats && AC.isCFGBuilt()) { 2240 ++NumFunctionsAnalyzed; 2241 if (CFG *cfg = AC.getCFG()) { 2242 // If we successfully built a CFG for this context, record some more 2243 // detail information about it. 2244 NumCFGBlocks += cfg->getNumBlockIDs(); 2245 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction, 2246 cfg->getNumBlockIDs()); 2247 } else { 2248 ++NumFunctionsWithBadCFGs; 2249 } 2250 } 2251 } 2252 2253 void clang::sema::AnalysisBasedWarnings::PrintStats() const { 2254 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n"; 2255 2256 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs; 2257 unsigned AvgCFGBlocksPerFunction = 2258 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt; 2259 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed (" 2260 << NumFunctionsWithBadCFGs << " w/o CFGs).\n" 2261 << " " << NumCFGBlocks << " CFG blocks built.\n" 2262 << " " << AvgCFGBlocksPerFunction 2263 << " average CFG blocks per function.\n" 2264 << " " << MaxCFGBlocksPerFunction 2265 << " max CFG blocks per function.\n"; 2266 2267 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0 2268 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions; 2269 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0 2270 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions; 2271 llvm::errs() << NumUninitAnalysisFunctions 2272 << " functions analyzed for uninitialiazed variables\n" 2273 << " " << NumUninitAnalysisVariables << " variables analyzed.\n" 2274 << " " << AvgUninitVariablesPerFunction 2275 << " average variables per function.\n" 2276 << " " << MaxUninitAnalysisVariablesPerFunction 2277 << " max variables per function.\n" 2278 << " " << NumUninitAnalysisBlockVisits << " block visits.\n" 2279 << " " << AvgUninitBlockVisitsPerFunction 2280 << " average block visits per function.\n" 2281 << " " << MaxUninitAnalysisBlockVisitsPerFunction 2282 << " max block visits per function.\n"; 2283 } 2284