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