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