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