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