1 //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
50 using namespace clang;
52 //===----------------------------------------------------------------------===//
53 // Unreachable code analysis.
54 //===----------------------------------------------------------------------===//
57 class UnreachableCodeHandler : public reachable_code::Callback {
59 SourceRange PreviousSilenceableCondVal;
62 UnreachableCodeHandler(Sema &s) : S(s) {}
64 void HandleUnreachable(reachable_code::UnreachableKind UK,
66 SourceRange SilenceableCondVal,
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)
75 PreviousSilenceableCondVal = SilenceableCondVal;
77 unsigned diag = diag::warn_unreachable;
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
82 case reachable_code::UK_Return:
83 diag = diag::warn_unreachable_return;
85 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
88 case reachable_code::UK_Other:
92 S.Diag(L, diag) << R1 << R2;
94 SourceLocation Open = SilenceableCondVal.getBegin();
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, ")");
106 } // anonymous namespace
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.
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()))
120 UnreachableCodeHandler UC(S);
121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
125 /// \brief Warn on logical operator errors in CFGBuilder
126 class LogicalErrorHandler : public CFGCallback {
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
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))
145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
164 } // anonymous namespace
166 //===----------------------------------------------------------------------===//
167 // Check for infinite self-recursion in functions
168 //===----------------------------------------------------------------------===//
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)
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
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())) {
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
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 {
208 FoundPathWithNoRecursiveCall
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) {
215 const unsigned ExitID = cfg->getExit().getBlockID();
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;
221 // Make the processing stack and seed it with the entry block.
222 SmallVector<CFGBlock *, 16> Stack;
223 Stack.push_back(&cfg->getEntry());
225 while (!Stack.empty()) {
226 CFGBlock *CurBlock = Stack.back();
229 unsigned ID = CurBlock->getBlockID();
230 RecursiveState CurState = States[ID];
232 if (CurState == FoundPathWithNoRecursiveCall) {
233 // Found a path to the exit node without a recursive call.
237 // Only change state if the block has a recursive call.
238 if (hasRecursiveCallInPath(FD, *CurBlock))
239 CurState = FoundPath;
242 // Loop over successor blocks and add them to the Stack if their state
244 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
246 unsigned next_ID = (*I)->getBlockID();
247 if (States[next_ID] < CurState) {
248 States[next_ID] = CurState;
254 // Return true if the exit node is reachable, and only reachable through
256 return States[ExitID] == FoundPath;
259 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
260 const Stmt *Body, AnalysisDeclContext &AC) {
261 FD = FD->getCanonicalDecl();
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)
269 CFG *cfg = AC.getCFG();
272 // If the exit block is unreachable, skip processing the function.
273 if (cfg->getExit().pred_empty())
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);
281 //===----------------------------------------------------------------------===//
282 // Check for missing return value.
283 //===----------------------------------------------------------------------===//
285 enum ControlFlowKind {
290 NeverFallThroughOrReturn
293 /// CheckFallThrough - Check that we don't fall off the end of a
294 /// Statement that should return a value.
296 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
297 /// MaybeFallThrough iff we might or might not fall off the end,
298 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
299 /// return. We assume NeverFallThrough iff we never fall off the end of the
300 /// statement but we may return. We assume that functions not marked noreturn
302 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
303 CFG *cfg = AC.getCFG();
304 if (!cfg) return UnknownFallThrough;
306 // The CFG leaves in dead things, and we don't want the dead code paths to
307 // confuse us, so we mark all live things first.
308 llvm::BitVector live(cfg->getNumBlockIDs());
309 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
312 bool AddEHEdges = AC.getAddEHEdges();
313 if (!AddEHEdges && count != cfg->getNumBlockIDs())
314 // When there are things remaining dead, and we didn't add EH edges
315 // from CallExprs to the catch clauses, we have to go back and
316 // mark them as live.
317 for (const auto *B : *cfg) {
318 if (!live[B->getBlockID()]) {
319 if (B->pred_begin() == B->pred_end()) {
320 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
321 // When not adding EH edges from calls, catch clauses
322 // can otherwise seem dead. Avoid noting them as dead.
323 count += reachable_code::ScanReachableFromBlock(B, live);
329 // Now we know what is live, we check the live precessors of the exit block
330 // and look for fall through paths, being careful to ignore normal returns,
331 // and exceptional paths.
332 bool HasLiveReturn = false;
333 bool HasFakeEdge = false;
334 bool HasPlainEdge = false;
335 bool HasAbnormalEdge = false;
337 // Ignore default cases that aren't likely to be reachable because all
338 // enums in a switch(X) have explicit case statements.
339 CFGBlock::FilterOptions FO;
340 FO.IgnoreDefaultsWithCoveredEnums = 1;
342 for (CFGBlock::filtered_pred_iterator
343 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
344 const CFGBlock& B = **I;
345 if (!live[B.getBlockID()])
348 // Skip blocks which contain an element marked as no-return. They don't
349 // represent actually viable edges into the exit block, so mark them as
351 if (B.hasNoReturnElement()) {
352 HasAbnormalEdge = true;
356 // Destructors can appear after the 'return' in the CFG. This is
357 // normal. We need to look pass the destructors for the return
358 // statement (if it exists).
359 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
361 for ( ; ri != re ; ++ri)
362 if (ri->getAs<CFGStmt>())
365 // No more CFGElements in the block?
367 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
368 HasAbnormalEdge = true;
371 // A labeled empty statement, or the entry block...
376 CFGStmt CS = ri->castAs<CFGStmt>();
377 const Stmt *S = CS.getStmt();
378 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
379 HasLiveReturn = true;
382 if (isa<ObjCAtThrowStmt>(S)) {
386 if (isa<CXXThrowExpr>(S)) {
390 if (isa<MSAsmStmt>(S)) {
391 // TODO: Verify this is correct.
393 HasLiveReturn = true;
396 if (isa<CXXTryStmt>(S)) {
397 HasAbnormalEdge = true;
400 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
402 HasAbnormalEdge = true;
410 return NeverFallThrough;
411 return NeverFallThroughOrReturn;
413 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
414 return MaybeFallThrough;
415 // This says AlwaysFallThrough for calls to functions that are not marked
416 // noreturn, that don't return. If people would like this warning to be more
417 // accurate, such functions should be marked as noreturn.
418 return AlwaysFallThrough;
423 struct CheckFallThroughDiagnostics {
424 unsigned diag_MaybeFallThrough_HasNoReturn;
425 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
426 unsigned diag_AlwaysFallThrough_HasNoReturn;
427 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
428 unsigned diag_NeverFallThroughOrReturn;
429 enum { Function, Block, Lambda, Coroutine } funMode;
430 SourceLocation FuncLoc;
432 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
433 CheckFallThroughDiagnostics D;
434 D.FuncLoc = Func->getLocation();
435 D.diag_MaybeFallThrough_HasNoReturn =
436 diag::warn_falloff_noreturn_function;
437 D.diag_MaybeFallThrough_ReturnsNonVoid =
438 diag::warn_maybe_falloff_nonvoid_function;
439 D.diag_AlwaysFallThrough_HasNoReturn =
440 diag::warn_falloff_noreturn_function;
441 D.diag_AlwaysFallThrough_ReturnsNonVoid =
442 diag::warn_falloff_nonvoid_function;
444 // Don't suggest that virtual functions be marked "noreturn", since they
445 // might be overridden by non-noreturn functions.
446 bool isVirtualMethod = false;
447 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
448 isVirtualMethod = Method->isVirtual();
450 // Don't suggest that template instantiations be marked "noreturn"
451 bool isTemplateInstantiation = false;
452 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
453 isTemplateInstantiation = Function->isTemplateInstantiation();
455 if (!isVirtualMethod && !isTemplateInstantiation)
456 D.diag_NeverFallThroughOrReturn =
457 diag::warn_suggest_noreturn_function;
459 D.diag_NeverFallThroughOrReturn = 0;
461 D.funMode = Function;
465 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
466 CheckFallThroughDiagnostics D;
467 D.FuncLoc = Func->getLocation();
468 D.diag_MaybeFallThrough_HasNoReturn = 0;
469 D.diag_MaybeFallThrough_ReturnsNonVoid =
470 diag::warn_maybe_falloff_nonvoid_coroutine;
471 D.diag_AlwaysFallThrough_HasNoReturn = 0;
472 D.diag_AlwaysFallThrough_ReturnsNonVoid =
473 diag::warn_falloff_nonvoid_coroutine;
474 D.funMode = Coroutine;
478 static CheckFallThroughDiagnostics MakeForBlock() {
479 CheckFallThroughDiagnostics D;
480 D.diag_MaybeFallThrough_HasNoReturn =
481 diag::err_noreturn_block_has_return_expr;
482 D.diag_MaybeFallThrough_ReturnsNonVoid =
483 diag::err_maybe_falloff_nonvoid_block;
484 D.diag_AlwaysFallThrough_HasNoReturn =
485 diag::err_noreturn_block_has_return_expr;
486 D.diag_AlwaysFallThrough_ReturnsNonVoid =
487 diag::err_falloff_nonvoid_block;
488 D.diag_NeverFallThroughOrReturn = 0;
493 static CheckFallThroughDiagnostics MakeForLambda() {
494 CheckFallThroughDiagnostics D;
495 D.diag_MaybeFallThrough_HasNoReturn =
496 diag::err_noreturn_lambda_has_return_expr;
497 D.diag_MaybeFallThrough_ReturnsNonVoid =
498 diag::warn_maybe_falloff_nonvoid_lambda;
499 D.diag_AlwaysFallThrough_HasNoReturn =
500 diag::err_noreturn_lambda_has_return_expr;
501 D.diag_AlwaysFallThrough_ReturnsNonVoid =
502 diag::warn_falloff_nonvoid_lambda;
503 D.diag_NeverFallThroughOrReturn = 0;
508 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
509 bool HasNoReturn) const {
510 if (funMode == Function) {
511 return (ReturnsVoid ||
512 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
515 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
518 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
520 if (funMode == Coroutine) {
521 return (ReturnsVoid ||
522 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
523 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
527 // For blocks / lambdas.
528 return ReturnsVoid && !HasNoReturn;
532 } // anonymous namespace
534 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
535 /// function that should return a value. Check that we don't fall off the end
536 /// of a noreturn function. We assume that functions and blocks not marked
537 /// noreturn will return.
538 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
539 const BlockExpr *blkExpr,
540 const CheckFallThroughDiagnostics& CD,
541 AnalysisDeclContext &AC) {
543 bool ReturnsVoid = false;
544 bool HasNoReturn = false;
545 bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
547 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
548 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
549 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
551 ReturnsVoid = FD->getReturnType()->isVoidType();
552 HasNoReturn = FD->isNoReturn();
554 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
555 ReturnsVoid = MD->getReturnType()->isVoidType();
556 HasNoReturn = MD->hasAttr<NoReturnAttr>();
558 else if (isa<BlockDecl>(D)) {
559 QualType BlockTy = blkExpr->getType();
560 if (const FunctionType *FT =
561 BlockTy->getPointeeType()->getAs<FunctionType>()) {
562 if (FT->getReturnType()->isVoidType())
564 if (FT->getNoReturnAttr())
569 DiagnosticsEngine &Diags = S.getDiagnostics();
571 // Short circuit for compilation speed.
572 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
574 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
575 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
577 S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
581 // Either in a function body compound statement, or a function-try-block.
582 switch (CheckFallThrough(AC)) {
583 case UnknownFallThrough:
586 case MaybeFallThrough:
588 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
589 else if (!ReturnsVoid)
590 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
592 case AlwaysFallThrough:
594 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
595 else if (!ReturnsVoid)
596 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
598 case NeverFallThroughOrReturn:
599 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
600 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
601 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
602 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
603 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
605 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
609 case NeverFallThrough:
614 //===----------------------------------------------------------------------===//
616 //===----------------------------------------------------------------------===//
619 /// ContainsReference - A visitor class to search for references to
620 /// a particular declaration (the needle) within any evaluated component of an
621 /// expression (recursively).
622 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
624 const DeclRefExpr *Needle;
627 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
629 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
630 : Inherited(Context), FoundReference(false), Needle(Needle) {}
632 void VisitExpr(const Expr *E) {
633 // Stop evaluating if we already have a reference.
637 Inherited::VisitExpr(E);
640 void VisitDeclRefExpr(const DeclRefExpr *E) {
642 FoundReference = true;
644 Inherited::VisitDeclRefExpr(E);
647 bool doesContainReference() const { return FoundReference; }
649 } // anonymous namespace
651 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
652 QualType VariableTy = VD->getType().getCanonicalType();
653 if (VariableTy->isBlockPointerType() &&
654 !VD->hasAttr<BlocksAttr>()) {
655 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
657 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
661 // Don't issue a fixit if there is already an initializer.
665 // Don't suggest a fixit inside macros.
666 if (VD->getLocEnd().isMacroID())
669 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
671 // Suggest possible initialization (if any).
672 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
676 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
677 << FixItHint::CreateInsertion(Loc, Init);
681 /// Create a fixit to remove an if-like statement, on the assumption that its
682 /// condition is CondVal.
683 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
684 const Stmt *Else, bool CondVal,
685 FixItHint &Fixit1, FixItHint &Fixit2) {
687 // If condition is always true, remove all but the 'then'.
688 Fixit1 = FixItHint::CreateRemoval(
689 CharSourceRange::getCharRange(If->getLocStart(),
690 Then->getLocStart()));
692 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
693 Fixit2 = FixItHint::CreateRemoval(
694 SourceRange(ElseKwLoc, Else->getLocEnd()));
697 // If condition is always false, remove all but the 'else'.
699 Fixit1 = FixItHint::CreateRemoval(
700 CharSourceRange::getCharRange(If->getLocStart(),
701 Else->getLocStart()));
703 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
707 /// DiagUninitUse -- Helper function to produce a diagnostic for an
708 /// uninitialized use of a variable.
709 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
710 bool IsCapturedByBlock) {
711 bool Diagnosed = false;
713 switch (Use.getKind()) {
714 case UninitUse::Always:
715 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
716 << VD->getDeclName() << IsCapturedByBlock
717 << Use.getUser()->getSourceRange();
720 case UninitUse::AfterDecl:
721 case UninitUse::AfterCall:
722 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
723 << VD->getDeclName() << IsCapturedByBlock
724 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
725 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
726 << VD->getSourceRange();
727 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
728 << IsCapturedByBlock << Use.getUser()->getSourceRange();
731 case UninitUse::Maybe:
732 case UninitUse::Sometimes:
733 // Carry on to report sometimes-uninitialized branches, if possible,
734 // or a 'may be used uninitialized' diagnostic otherwise.
738 // Diagnose each branch which leads to a sometimes-uninitialized use.
739 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
741 assert(Use.getKind() == UninitUse::Sometimes);
743 const Expr *User = Use.getUser();
744 const Stmt *Term = I->Terminator;
746 // Information used when building the diagnostic.
751 // FixIts to suppress the diagnostic by removing the dead condition.
752 // For all binary terminators, branch 0 is taken if the condition is true,
753 // and branch 1 is taken if the condition is false.
754 int RemoveDiagKind = -1;
755 const char *FixitStr =
756 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
757 : (I->Output ? "1" : "0");
758 FixItHint Fixit1, Fixit2;
760 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
762 // Don't know how to report this. Just fall back to 'may be used
763 // uninitialized'. FIXME: Can this happen?
766 // "condition is true / condition is false".
767 case Stmt::IfStmtClass: {
768 const IfStmt *IS = cast<IfStmt>(Term);
771 Range = IS->getCond()->getSourceRange();
773 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
774 I->Output, Fixit1, Fixit2);
777 case Stmt::ConditionalOperatorClass: {
778 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
781 Range = CO->getCond()->getSourceRange();
783 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
784 I->Output, Fixit1, Fixit2);
787 case Stmt::BinaryOperatorClass: {
788 const BinaryOperator *BO = cast<BinaryOperator>(Term);
789 if (!BO->isLogicalOp())
792 Str = BO->getOpcodeStr();
793 Range = BO->getLHS()->getSourceRange();
795 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
796 (BO->getOpcode() == BO_LOr && !I->Output))
797 // true && y -> y, false || y -> y.
798 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
799 BO->getOperatorLoc()));
801 // false && y -> false, true || y -> true.
802 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
806 // "loop is entered / loop is exited".
807 case Stmt::WhileStmtClass:
810 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
812 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
814 case Stmt::ForStmtClass:
817 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
820 Fixit1 = FixItHint::CreateRemoval(Range);
822 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
824 case Stmt::CXXForRangeStmtClass:
825 if (I->Output == 1) {
826 // The use occurs if a range-based for loop's body never executes.
827 // That may be impossible, and there's no syntactic fix for this,
828 // so treat it as a 'may be uninitialized' case.
833 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
836 // "condition is true / loop is exited".
837 case Stmt::DoStmtClass:
840 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
842 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
845 // "switch case is taken".
846 case Stmt::CaseStmtClass:
849 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
851 case Stmt::DefaultStmtClass:
854 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
858 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
859 << VD->getDeclName() << IsCapturedByBlock << DiagKind
860 << Str << I->Output << Range;
861 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
862 << IsCapturedByBlock << User->getSourceRange();
863 if (RemoveDiagKind != -1)
864 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
865 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
871 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
872 << VD->getDeclName() << IsCapturedByBlock
873 << Use.getUser()->getSourceRange();
876 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
877 /// uninitialized variable. This manages the different forms of diagnostic
878 /// emitted for particular types of uses. Returns true if the use was diagnosed
879 /// as a warning. If a particular use is one we omit warnings for, returns
881 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
882 const UninitUse &Use,
883 bool alwaysReportSelfInit = false) {
884 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
885 // Inspect the initializer of the variable declaration which is
886 // being referenced prior to its initialization. We emit
887 // specialized diagnostics for self-initialization, and we
888 // specifically avoid warning about self references which take the
893 // This is used to indicate to GCC that 'x' is intentionally left
894 // uninitialized. Proven code paths which access 'x' in
895 // an uninitialized state after this will still warn.
896 if (const Expr *Initializer = VD->getInit()) {
897 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
900 ContainsReference CR(S.Context, DRE);
901 CR.Visit(Initializer);
902 if (CR.doesContainReference()) {
903 S.Diag(DRE->getLocStart(),
904 diag::warn_uninit_self_reference_in_init)
905 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
910 DiagUninitUse(S, VD, Use, false);
912 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
913 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
914 S.Diag(BE->getLocStart(),
915 diag::warn_uninit_byref_blockvar_captured_by_block)
916 << VD->getDeclName();
918 DiagUninitUse(S, VD, Use, true);
921 // Report where the variable was declared when the use wasn't within
922 // the initializer of that declaration & we didn't already suggest
923 // an initialization fixit.
924 if (!SuggestInitializationFixit(S, VD))
925 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
926 << VD->getDeclName();
932 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
934 FallthroughMapper(Sema &S)
935 : FoundSwitchStatements(false),
939 bool foundSwitchStatements() const { return FoundSwitchStatements; }
941 void markFallthroughVisited(const AttributedStmt *Stmt) {
942 bool Found = FallthroughStmts.erase(Stmt);
947 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
949 const AttrStmts &getFallthroughStmts() const {
950 return FallthroughStmts;
953 void fillReachableBlocks(CFG *Cfg) {
954 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
955 std::deque<const CFGBlock *> BlockQueue;
957 ReachableBlocks.insert(&Cfg->getEntry());
958 BlockQueue.push_back(&Cfg->getEntry());
959 // Mark all case blocks reachable to avoid problems with switching on
960 // constants, covered enums, etc.
961 // These blocks can contain fall-through annotations, and we don't want to
962 // issue a warn_fallthrough_attr_unreachable for them.
963 for (const auto *B : *Cfg) {
964 const Stmt *L = B->getLabel();
965 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
966 BlockQueue.push_back(B);
969 while (!BlockQueue.empty()) {
970 const CFGBlock *P = BlockQueue.front();
971 BlockQueue.pop_front();
972 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
975 if (*I && ReachableBlocks.insert(*I).second)
976 BlockQueue.push_back(*I);
981 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
982 bool IsTemplateInstantiation) {
983 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
985 int UnannotatedCnt = 0;
988 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
989 while (!BlockQueue.empty()) {
990 const CFGBlock *P = BlockQueue.front();
991 BlockQueue.pop_front();
994 const Stmt *Term = P->getTerminator();
995 if (Term && isa<SwitchStmt>(Term))
996 continue; // Switch statement, good.
998 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
999 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1000 continue; // Previous case label has no statements, good.
1002 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1003 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1004 continue; // Case label is preceded with a normal label, good.
1006 if (!ReachableBlocks.count(P)) {
1007 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1008 ElemEnd = P->rend();
1009 ElemIt != ElemEnd; ++ElemIt) {
1010 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1011 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1012 // Don't issue a warning for an unreachable fallthrough
1013 // attribute in template instantiations as it may not be
1014 // unreachable in all instantiations of the template.
1015 if (!IsTemplateInstantiation)
1016 S.Diag(AS->getLocStart(),
1017 diag::warn_fallthrough_attr_unreachable);
1018 markFallthroughVisited(AS);
1022 // Don't care about other unreachable statements.
1025 // If there are no unreachable statements, this may be a special
1028 // A a; // A has a destructor.
1031 // // <<<< This place is represented by a 'hanging' CFG block.
1036 const Stmt *LastStmt = getLastStmt(*P);
1037 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1038 markFallthroughVisited(AS);
1040 continue; // Fallthrough annotation, good.
1043 if (!LastStmt) { // This block contains no executable statements.
1044 // Traverse its predecessors.
1045 std::copy(P->pred_begin(), P->pred_end(),
1046 std::back_inserter(BlockQueue));
1052 return !!UnannotatedCnt;
1055 // RecursiveASTVisitor setup.
1056 bool shouldWalkTypesOfTypeLocs() const { return false; }
1058 bool VisitAttributedStmt(AttributedStmt *S) {
1059 if (asFallThroughAttr(S))
1060 FallthroughStmts.insert(S);
1064 bool VisitSwitchStmt(SwitchStmt *S) {
1065 FoundSwitchStatements = true;
1069 // We don't want to traverse local type declarations. We analyze their
1070 // methods separately.
1071 bool TraverseDecl(Decl *D) { return true; }
1073 // We analyze lambda bodies separately. Skip them here.
1074 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1078 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1079 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1080 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1086 static const Stmt *getLastStmt(const CFGBlock &B) {
1087 if (const Stmt *Term = B.getTerminator())
1089 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1091 ElemIt != ElemEnd; ++ElemIt) {
1092 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1093 return CS->getStmt();
1095 // Workaround to detect a statement thrown out by CFGBuilder:
1096 // case X: {} case Y:
1097 // case X: ; case Y:
1098 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1099 if (!isa<SwitchCase>(SW->getSubStmt()))
1100 return SW->getSubStmt();
1105 bool FoundSwitchStatements;
1106 AttrStmts FallthroughStmts;
1108 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1110 } // anonymous namespace
1112 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1113 SourceLocation Loc) {
1114 TokenValue FallthroughTokens[] = {
1115 tok::l_square, tok::l_square,
1116 PP.getIdentifierInfo("fallthrough"),
1117 tok::r_square, tok::r_square
1120 TokenValue ClangFallthroughTokens[] = {
1121 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1122 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1123 tok::r_square, tok::r_square
1126 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1128 StringRef MacroName;
1129 if (PreferClangAttr)
1130 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1131 if (MacroName.empty())
1132 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1133 if (MacroName.empty() && !PreferClangAttr)
1134 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1135 if (MacroName.empty())
1136 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1140 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1142 // Only perform this analysis when using C++11. There is no good workflow
1143 // for this warning when not using C++11. There is no good way to silence
1144 // the warning (no attribute is available) unless we are using C++11's support
1145 // for generalized attributes. Once could use pragmas to silence the warning,
1146 // but as a general solution that is gross and not in the spirit of this
1149 // NOTE: This an intermediate solution. There are on-going discussions on
1150 // how to properly support this warning outside of C++11 with an annotation.
1151 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
1154 FallthroughMapper FM(S);
1155 FM.TraverseStmt(AC.getBody());
1157 if (!FM.foundSwitchStatements())
1160 if (PerFunction && FM.getFallthroughStmts().empty())
1163 CFG *Cfg = AC.getCFG();
1168 FM.fillReachableBlocks(Cfg);
1170 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1171 const Stmt *Label = B->getLabel();
1173 if (!Label || !isa<SwitchCase>(Label))
1178 bool IsTemplateInstantiation = false;
1179 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1180 IsTemplateInstantiation = Function->isTemplateInstantiation();
1181 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1182 IsTemplateInstantiation))
1185 S.Diag(Label->getLocStart(),
1186 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1187 : diag::warn_unannotated_fallthrough);
1189 if (!AnnotatedCnt) {
1190 SourceLocation L = Label->getLocStart();
1193 if (S.getLangOpts().CPlusPlus11) {
1194 const Stmt *Term = B->getTerminator();
1195 // Skip empty cases.
1196 while (B->empty() && !Term && B->succ_size() == 1) {
1197 B = *B->succ_begin();
1198 Term = B->getTerminator();
1200 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1201 Preprocessor &PP = S.getPreprocessor();
1202 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1203 SmallString<64> TextToInsert(AnnotationSpelling);
1204 TextToInsert += "; ";
1205 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1206 AnnotationSpelling <<
1207 FixItHint::CreateInsertion(L, TextToInsert);
1210 S.Diag(L, diag::note_insert_break_fixit) <<
1211 FixItHint::CreateInsertion(L, "break; ");
1215 for (const auto *F : FM.getFallthroughStmts())
1216 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
1219 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1224 switch (S->getStmtClass()) {
1225 case Stmt::ForStmtClass:
1226 case Stmt::WhileStmtClass:
1227 case Stmt::CXXForRangeStmtClass:
1228 case Stmt::ObjCForCollectionStmtClass:
1230 case Stmt::DoStmtClass: {
1231 const Expr *Cond = cast<DoStmt>(S)->getCond();
1233 if (!Cond->EvaluateAsInt(Val, Ctx))
1235 return Val.getBoolValue();
1240 } while ((S = PM.getParent(S)));
1245 static void diagnoseRepeatedUseOfWeak(Sema &S,
1246 const sema::FunctionScopeInfo *CurFn,
1248 const ParentMap &PM) {
1249 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1250 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1251 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1252 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1255 ASTContext &Ctx = S.getASTContext();
1257 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1259 // Extract all weak objects that are referenced more than once.
1260 SmallVector<StmtUsesPair, 8> UsesByStmt;
1261 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1263 const WeakUseVector &Uses = I->second;
1265 // Find the first read of the weak object.
1266 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1267 for ( ; UI != UE; ++UI) {
1272 // If there were only writes to this object, don't warn.
1276 // If there was only one read, followed by any number of writes, and the
1277 // read is not within a loop, don't warn. Additionally, don't warn in a
1278 // loop if the base object is a local variable -- local variables are often
1279 // changed in loops.
1280 if (UI == Uses.begin()) {
1281 WeakUseVector::const_iterator UI2 = UI;
1282 for (++UI2; UI2 != UE; ++UI2)
1283 if (UI2->isUnsafe())
1287 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1290 const WeakObjectProfileTy &Profile = I->first;
1291 if (!Profile.isExactProfile())
1294 const NamedDecl *Base = Profile.getBase();
1296 Base = Profile.getProperty();
1297 assert(Base && "A profile always has a base or property.");
1299 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1300 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1305 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1308 if (UsesByStmt.empty())
1311 // Sort by first use so that we emit the warnings in a deterministic order.
1312 SourceManager &SM = S.getSourceManager();
1313 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1314 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1315 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1316 RHS.first->getLocStart());
1319 // Classify the current code body for better warning text.
1320 // This enum should stay in sync with the cases in
1321 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1322 // FIXME: Should we use a common classification enum and the same set of
1323 // possibilities all throughout Sema?
1331 if (isa<sema::BlockScopeInfo>(CurFn))
1332 FunctionKind = Block;
1333 else if (isa<sema::LambdaScopeInfo>(CurFn))
1334 FunctionKind = Lambda;
1335 else if (isa<ObjCMethodDecl>(D))
1336 FunctionKind = Method;
1338 FunctionKind = Function;
1340 // Iterate through the sorted problems and emit warnings for each.
1341 for (const auto &P : UsesByStmt) {
1342 const Stmt *FirstRead = P.first;
1343 const WeakObjectProfileTy &Key = P.second->first;
1344 const WeakUseVector &Uses = P.second->second;
1346 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1347 // may not contain enough information to determine that these are different
1348 // properties. We can only be 100% sure of a repeated use in certain cases,
1349 // and we adjust the diagnostic kind accordingly so that the less certain
1350 // case can be turned off if it is too noisy.
1352 if (Key.isExactProfile())
1353 DiagKind = diag::warn_arc_repeated_use_of_weak;
1355 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1357 // Classify the weak object being accessed for better warning text.
1358 // This enum should stay in sync with the cases in
1359 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1367 const NamedDecl *KeyProp = Key.getProperty();
1368 if (isa<VarDecl>(KeyProp))
1369 ObjectKind = Variable;
1370 else if (isa<ObjCPropertyDecl>(KeyProp))
1371 ObjectKind = Property;
1372 else if (isa<ObjCMethodDecl>(KeyProp))
1373 ObjectKind = ImplicitProperty;
1374 else if (isa<ObjCIvarDecl>(KeyProp))
1377 llvm_unreachable("Unexpected weak object kind!");
1379 // Do not warn about IBOutlet weak property receivers being set to null
1380 // since they are typically only used from the main thread.
1381 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1382 if (Prop->hasAttr<IBOutletAttr>())
1385 // Show the first time the object was read.
1386 S.Diag(FirstRead->getLocStart(), DiagKind)
1387 << int(ObjectKind) << KeyProp << int(FunctionKind)
1388 << FirstRead->getSourceRange();
1390 // Print all the other accesses as notes.
1391 for (const auto &Use : Uses) {
1392 if (Use.getUseExpr() == FirstRead)
1394 S.Diag(Use.getUseExpr()->getLocStart(),
1395 diag::note_arc_weak_also_accessed_here)
1396 << Use.getUseExpr()->getSourceRange();
1402 class UninitValsDiagReporter : public UninitVariablesHandler {
1404 typedef SmallVector<UninitUse, 2> UsesVec;
1405 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1406 // Prefer using MapVector to DenseMap, so that iteration order will be
1407 // the same as insertion order. This is needed to obtain a deterministic
1408 // order of diagnostics when calling flushDiagnostics().
1409 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1413 UninitValsDiagReporter(Sema &S) : S(S) {}
1414 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1416 MappedType &getUses(const VarDecl *vd) {
1417 MappedType &V = uses[vd];
1418 if (!V.getPointer())
1419 V.setPointer(new UsesVec());
1423 void handleUseOfUninitVariable(const VarDecl *vd,
1424 const UninitUse &use) override {
1425 getUses(vd).getPointer()->push_back(use);
1428 void handleSelfInit(const VarDecl *vd) override {
1429 getUses(vd).setInt(true);
1432 void flushDiagnostics() {
1433 for (const auto &P : uses) {
1434 const VarDecl *vd = P.first;
1435 const MappedType &V = P.second;
1437 UsesVec *vec = V.getPointer();
1438 bool hasSelfInit = V.getInt();
1440 // Specially handle the case where we have uses of an uninitialized
1441 // variable, but the root cause is an idiomatic self-init. We want
1442 // to report the diagnostic at the self-init since that is the root cause.
1443 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1444 DiagnoseUninitializedUse(S, vd,
1445 UninitUse(vd->getInit()->IgnoreParenCasts(),
1446 /* isAlwaysUninit */ true),
1447 /* alwaysReportSelfInit */ true);
1449 // Sort the uses by their SourceLocations. While not strictly
1450 // guaranteed to produce them in line/column order, this will provide
1451 // a stable ordering.
1452 std::sort(vec->begin(), vec->end(),
1453 [](const UninitUse &a, const UninitUse &b) {
1454 // Prefer a more confident report over a less confident one.
1455 if (a.getKind() != b.getKind())
1456 return a.getKind() > b.getKind();
1457 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1460 for (const auto &U : *vec) {
1461 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1462 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1464 if (DiagnoseUninitializedUse(S, vd, Use))
1465 // Skip further diagnostics for this variable. We try to warn only
1466 // on the first point at which a variable is used uninitialized.
1471 // Release the uses vector.
1479 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1480 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1481 return U.getKind() == UninitUse::Always ||
1482 U.getKind() == UninitUse::AfterCall ||
1483 U.getKind() == UninitUse::AfterDecl;
1487 } // anonymous namespace
1491 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1492 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1493 typedef std::list<DelayedDiag> DiagList;
1495 struct SortDiagBySourceLocation {
1497 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1499 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1500 // Although this call will be slow, this is only called when outputting
1501 // multiple warnings.
1502 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1505 } // anonymous namespace
1506 } // namespace clang
1508 //===----------------------------------------------------------------------===//
1510 //===----------------------------------------------------------------------===//
1512 namespace threadSafety {
1514 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1517 SourceLocation FunLocation, FunEndLocation;
1519 const FunctionDecl *CurrentFunction;
1522 OptionalNotes getNotes() const {
1523 if (Verbose && CurrentFunction) {
1524 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1525 S.PDiag(diag::note_thread_warning_in_fun)
1526 << CurrentFunction->getNameAsString());
1527 return OptionalNotes(1, FNote);
1529 return OptionalNotes();
1532 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1533 OptionalNotes ONS(1, Note);
1534 if (Verbose && CurrentFunction) {
1535 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1536 S.PDiag(diag::note_thread_warning_in_fun)
1537 << CurrentFunction->getNameAsString());
1538 ONS.push_back(std::move(FNote));
1543 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1544 const PartialDiagnosticAt &Note2) const {
1546 ONS.push_back(Note1);
1547 ONS.push_back(Note2);
1548 if (Verbose && CurrentFunction) {
1549 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1550 S.PDiag(diag::note_thread_warning_in_fun)
1551 << CurrentFunction->getNameAsString());
1552 ONS.push_back(std::move(FNote));
1558 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1559 SourceLocation Loc) {
1560 // Gracefully handle rare cases when the analysis can't get a more
1561 // precise source location.
1564 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1565 Warnings.emplace_back(std::move(Warning), getNotes());
1569 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1570 : S(S), FunLocation(FL), FunEndLocation(FEL),
1571 CurrentFunction(nullptr), Verbose(false) {}
1573 void setVerbose(bool b) { Verbose = b; }
1575 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1576 /// We need to output diagnostics produced while iterating through
1577 /// the lockset in deterministic order, so this function orders diagnostics
1578 /// and outputs them.
1579 void emitDiagnostics() {
1580 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1581 for (const auto &Diag : Warnings) {
1582 S.Diag(Diag.first.first, Diag.first.second);
1583 for (const auto &Note : Diag.second)
1584 S.Diag(Note.first, Note.second);
1588 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1589 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1591 Warnings.emplace_back(std::move(Warning), getNotes());
1594 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1595 SourceLocation Loc) override {
1596 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1599 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1600 LockKind Expected, LockKind Received,
1601 SourceLocation Loc) override {
1602 if (Loc.isInvalid())
1604 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1605 << Kind << LockName << Received
1607 Warnings.emplace_back(std::move(Warning), getNotes());
1610 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1611 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1614 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1615 SourceLocation LocLocked,
1616 SourceLocation LocEndOfScope,
1617 LockErrorKind LEK) override {
1618 unsigned DiagID = 0;
1620 case LEK_LockedSomePredecessors:
1621 DiagID = diag::warn_lock_some_predecessors;
1623 case LEK_LockedSomeLoopIterations:
1624 DiagID = diag::warn_expecting_lock_held_on_loop;
1626 case LEK_LockedAtEndOfFunction:
1627 DiagID = diag::warn_no_unlock;
1629 case LEK_NotLockedAtEndOfFunction:
1630 DiagID = diag::warn_expecting_locked;
1633 if (LocEndOfScope.isInvalid())
1634 LocEndOfScope = FunEndLocation;
1636 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1638 if (LocLocked.isValid()) {
1639 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1641 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1644 Warnings.emplace_back(std::move(Warning), getNotes());
1647 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1648 SourceLocation Loc1,
1649 SourceLocation Loc2) override {
1650 PartialDiagnosticAt Warning(Loc1,
1651 S.PDiag(diag::warn_lock_exclusive_and_shared)
1652 << Kind << LockName);
1653 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1654 << Kind << LockName);
1655 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1658 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1659 ProtectedOperationKind POK, AccessKind AK,
1660 SourceLocation Loc) override {
1661 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1662 "Only works for variables");
1663 unsigned DiagID = POK == POK_VarAccess?
1664 diag::warn_variable_requires_any_lock:
1665 diag::warn_var_deref_requires_any_lock;
1666 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1667 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1668 Warnings.emplace_back(std::move(Warning), getNotes());
1671 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1672 ProtectedOperationKind POK, Name LockName,
1673 LockKind LK, SourceLocation Loc,
1674 Name *PossibleMatch) override {
1675 unsigned DiagID = 0;
1676 if (PossibleMatch) {
1679 DiagID = diag::warn_variable_requires_lock_precise;
1681 case POK_VarDereference:
1682 DiagID = diag::warn_var_deref_requires_lock_precise;
1684 case POK_FunctionCall:
1685 DiagID = diag::warn_fun_requires_lock_precise;
1688 DiagID = diag::warn_guarded_pass_by_reference;
1690 case POK_PtPassByRef:
1691 DiagID = diag::warn_pt_guarded_pass_by_reference;
1694 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1695 << D->getNameAsString()
1697 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1699 if (Verbose && POK == POK_VarAccess) {
1700 PartialDiagnosticAt VNote(D->getLocation(),
1701 S.PDiag(diag::note_guarded_by_declared_here)
1702 << D->getNameAsString());
1703 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1705 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1709 DiagID = diag::warn_variable_requires_lock;
1711 case POK_VarDereference:
1712 DiagID = diag::warn_var_deref_requires_lock;
1714 case POK_FunctionCall:
1715 DiagID = diag::warn_fun_requires_lock;
1718 DiagID = diag::warn_guarded_pass_by_reference;
1720 case POK_PtPassByRef:
1721 DiagID = diag::warn_pt_guarded_pass_by_reference;
1724 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1725 << D->getNameAsString()
1727 if (Verbose && POK == POK_VarAccess) {
1728 PartialDiagnosticAt Note(D->getLocation(),
1729 S.PDiag(diag::note_guarded_by_declared_here)
1730 << D->getNameAsString());
1731 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1733 Warnings.emplace_back(std::move(Warning), getNotes());
1737 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1738 SourceLocation Loc) override {
1739 PartialDiagnosticAt Warning(Loc,
1740 S.PDiag(diag::warn_acquire_requires_negative_cap)
1741 << Kind << LockName << Neg);
1742 Warnings.emplace_back(std::move(Warning), getNotes());
1745 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1746 SourceLocation Loc) override {
1747 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1748 << Kind << FunName << LockName);
1749 Warnings.emplace_back(std::move(Warning), getNotes());
1752 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1753 SourceLocation Loc) override {
1754 PartialDiagnosticAt Warning(Loc,
1755 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1756 Warnings.emplace_back(std::move(Warning), getNotes());
1759 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1760 PartialDiagnosticAt Warning(Loc,
1761 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1762 Warnings.emplace_back(std::move(Warning), getNotes());
1765 void enterFunction(const FunctionDecl* FD) override {
1766 CurrentFunction = FD;
1769 void leaveFunction(const FunctionDecl* FD) override {
1770 CurrentFunction = nullptr;
1773 } // anonymous namespace
1774 } // namespace threadSafety
1775 } // namespace clang
1777 //===----------------------------------------------------------------------===//
1779 //===----------------------------------------------------------------------===//
1782 namespace consumed {
1784 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1791 ConsumedWarningsHandler(Sema &S) : S(S) {}
1793 void emitDiagnostics() override {
1794 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1795 for (const auto &Diag : Warnings) {
1796 S.Diag(Diag.first.first, Diag.first.second);
1797 for (const auto &Note : Diag.second)
1798 S.Diag(Note.first, Note.second);
1802 void warnLoopStateMismatch(SourceLocation Loc,
1803 StringRef VariableName) override {
1804 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1807 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1810 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1811 StringRef VariableName,
1812 StringRef ExpectedState,
1813 StringRef ObservedState) override {
1815 PartialDiagnosticAt Warning(Loc, S.PDiag(
1816 diag::warn_param_return_typestate_mismatch) << VariableName <<
1817 ExpectedState << ObservedState);
1819 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1822 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1823 StringRef ObservedState) override {
1825 PartialDiagnosticAt Warning(Loc, S.PDiag(
1826 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1828 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1831 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1832 StringRef TypeName) override {
1833 PartialDiagnosticAt Warning(Loc, S.PDiag(
1834 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1836 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1839 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1840 StringRef ObservedState) override {
1842 PartialDiagnosticAt Warning(Loc, S.PDiag(
1843 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1845 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1848 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1849 SourceLocation Loc) override {
1851 PartialDiagnosticAt Warning(Loc, S.PDiag(
1852 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1854 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1857 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1858 StringRef State, SourceLocation Loc) override {
1860 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1861 MethodName << VariableName << State);
1863 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1866 } // anonymous namespace
1867 } // namespace consumed
1868 } // namespace clang
1870 //===----------------------------------------------------------------------===//
1871 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1872 // warnings on a function, method, or block.
1873 //===----------------------------------------------------------------------===//
1875 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1876 enableCheckFallThrough = 1;
1877 enableCheckUnreachable = 0;
1878 enableThreadSafetyAnalysis = 0;
1879 enableConsumedAnalysis = 0;
1882 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1883 return (unsigned)!D.isIgnored(diag, SourceLocation());
1886 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1888 NumFunctionsAnalyzed(0),
1889 NumFunctionsWithBadCFGs(0),
1891 MaxCFGBlocksPerFunction(0),
1892 NumUninitAnalysisFunctions(0),
1893 NumUninitAnalysisVariables(0),
1894 MaxUninitAnalysisVariablesPerFunction(0),
1895 NumUninitAnalysisBlockVisits(0),
1896 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1898 using namespace diag;
1899 DiagnosticsEngine &D = S.getDiagnostics();
1901 DefaultPolicy.enableCheckUnreachable =
1902 isEnabled(D, warn_unreachable) ||
1903 isEnabled(D, warn_unreachable_break) ||
1904 isEnabled(D, warn_unreachable_return) ||
1905 isEnabled(D, warn_unreachable_loop_increment);
1907 DefaultPolicy.enableThreadSafetyAnalysis =
1908 isEnabled(D, warn_double_lock);
1910 DefaultPolicy.enableConsumedAnalysis =
1911 isEnabled(D, warn_use_in_invalid_state);
1914 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1915 for (const auto &D : fscope->PossiblyUnreachableDiags)
1916 S.Diag(D.Loc, D.PD);
1920 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1921 sema::FunctionScopeInfo *fscope,
1922 const Decl *D, const BlockExpr *blkExpr) {
1924 // We avoid doing analysis-based warnings when there are errors for
1926 // (1) The CFGs often can't be constructed (if the body is invalid), so
1927 // don't bother trying.
1928 // (2) The code already has problems; running the analysis just takes more
1930 DiagnosticsEngine &Diags = S.getDiagnostics();
1932 // Do not do any analysis for declarations in system headers if we are
1933 // going to just ignore them.
1934 if (Diags.getSuppressSystemWarnings() &&
1935 S.SourceMgr.isInSystemHeader(D->getLocation()))
1938 // For code in dependent contexts, we'll do this at instantiation time.
1939 if (cast<DeclContext>(D)->isDependentContext())
1942 if (Diags.hasUncompilableErrorOccurred()) {
1943 // Flush out any possibly unreachable diagnostics.
1944 flushDiagnostics(S, fscope);
1948 const Stmt *Body = D->getBody();
1951 // Construct the analysis context with the specified CFG build options.
1952 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
1954 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1955 // explosion for destructors that can result and the compile time hit.
1956 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1957 AC.getCFGBuildOptions().AddEHEdges = false;
1958 AC.getCFGBuildOptions().AddInitializers = true;
1959 AC.getCFGBuildOptions().AddImplicitDtors = true;
1960 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1961 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
1962 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
1964 // Force that certain expressions appear as CFGElements in the CFG. This
1965 // is used to speed up various analyses.
1966 // FIXME: This isn't the right factoring. This is here for initial
1967 // prototyping, but we need a way for analyses to say what expressions they
1968 // expect to always be CFGElements and then fill in the BuildOptions
1969 // appropriately. This is essentially a layering violation.
1970 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1971 P.enableConsumedAnalysis) {
1972 // Unreachable code analysis and thread safety require a linearized CFG.
1973 AC.getCFGBuildOptions().setAllAlwaysAdd();
1976 AC.getCFGBuildOptions()
1977 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1978 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1979 .setAlwaysAdd(Stmt::BlockExprClass)
1980 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1981 .setAlwaysAdd(Stmt::DeclRefExprClass)
1982 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1983 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1984 .setAlwaysAdd(Stmt::AttributedStmtClass);
1987 // Install the logical handler for -Wtautological-overlap-compare
1988 std::unique_ptr<LogicalErrorHandler> LEH;
1989 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1990 D->getLocStart())) {
1991 LEH.reset(new LogicalErrorHandler(S));
1992 AC.getCFGBuildOptions().Observer = LEH.get();
1995 // Emit delayed diagnostics.
1996 if (!fscope->PossiblyUnreachableDiags.empty()) {
1997 bool analyzed = false;
1999 // Register the expressions with the CFGBuilder.
2000 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2002 AC.registerForcedBlockExpression(D.stmt);
2007 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2008 bool processed = false;
2010 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
2011 CFGReverseBlockReachabilityAnalysis *cra =
2012 AC.getCFGReachablityAnalysis();
2013 // FIXME: We should be able to assert that block is non-null, but
2014 // the CFG analysis can skip potentially-evaluated expressions in
2015 // edge cases; see test/Sema/vla-2.c.
2017 // Can this block be reached from the entrance?
2018 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
2019 S.Diag(D.Loc, D.PD);
2024 // Emit the warning anyway if we cannot map to a basic block.
2025 S.Diag(D.Loc, D.PD);
2031 flushDiagnostics(S, fscope);
2034 // Warning: check missing 'return'
2035 if (P.enableCheckFallThrough) {
2036 const CheckFallThroughDiagnostics &CD =
2038 ? CheckFallThroughDiagnostics::MakeForBlock()
2039 : (isa<CXXMethodDecl>(D) &&
2040 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2041 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2042 ? CheckFallThroughDiagnostics::MakeForLambda()
2043 : (fscope->isCoroutine()
2044 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2045 : CheckFallThroughDiagnostics::MakeForFunction(D)));
2046 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
2049 // Warning: check for unreachable code
2050 if (P.enableCheckUnreachable) {
2051 // Only check for unreachable code on non-template instantiations.
2052 // Different template instantiations can effectively change the control-flow
2053 // and it is very difficult to prove that a snippet of code in a template
2054 // is unreachable for all instantiations.
2055 bool isTemplateInstantiation = false;
2056 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2057 isTemplateInstantiation = Function->isTemplateInstantiation();
2058 if (!isTemplateInstantiation)
2059 CheckUnreachable(S, AC);
2062 // Check for thread safety violations
2063 if (P.enableThreadSafetyAnalysis) {
2064 SourceLocation FL = AC.getDecl()->getLocation();
2065 SourceLocation FEL = AC.getDecl()->getLocEnd();
2066 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2067 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
2068 Reporter.setIssueBetaWarnings(true);
2069 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2070 Reporter.setVerbose(true);
2072 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2073 &S.ThreadSafetyDeclCache);
2074 Reporter.emitDiagnostics();
2077 // Check for violations of consumed properties.
2078 if (P.enableConsumedAnalysis) {
2079 consumed::ConsumedWarningsHandler WarningHandler(S);
2080 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2084 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2085 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2086 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2087 if (CFG *cfg = AC.getCFG()) {
2088 UninitValsDiagReporter reporter(S);
2089 UninitVariablesAnalysisStats stats;
2090 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2091 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2094 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2095 ++NumUninitAnalysisFunctions;
2096 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2097 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2098 MaxUninitAnalysisVariablesPerFunction =
2099 std::max(MaxUninitAnalysisVariablesPerFunction,
2100 stats.NumVariablesAnalyzed);
2101 MaxUninitAnalysisBlockVisitsPerFunction =
2102 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2103 stats.NumBlockVisits);
2108 bool FallThroughDiagFull =
2109 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2110 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2111 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2112 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2113 fscope->HasFallthroughStmt) {
2114 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2117 if (S.getLangOpts().ObjCWeak &&
2118 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2119 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2122 // Check for infinite self-recursion in functions
2123 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2124 D->getLocStart())) {
2125 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2126 checkRecursiveFunction(S, FD, Body, AC);
2130 // If none of the previous checks caused a CFG build, trigger one here
2131 // for -Wtautological-overlap-compare
2132 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2133 D->getLocStart())) {
2137 // Collect statistics about the CFG if it was built.
2138 if (S.CollectStats && AC.isCFGBuilt()) {
2139 ++NumFunctionsAnalyzed;
2140 if (CFG *cfg = AC.getCFG()) {
2141 // If we successfully built a CFG for this context, record some more
2142 // detail information about it.
2143 NumCFGBlocks += cfg->getNumBlockIDs();
2144 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2145 cfg->getNumBlockIDs());
2147 ++NumFunctionsWithBadCFGs;
2152 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2153 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2155 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2156 unsigned AvgCFGBlocksPerFunction =
2157 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2158 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2159 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2160 << " " << NumCFGBlocks << " CFG blocks built.\n"
2161 << " " << AvgCFGBlocksPerFunction
2162 << " average CFG blocks per function.\n"
2163 << " " << MaxCFGBlocksPerFunction
2164 << " max CFG blocks per function.\n";
2166 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2167 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2168 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2169 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2170 llvm::errs() << NumUninitAnalysisFunctions
2171 << " functions analyzed for uninitialiazed variables\n"
2172 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2173 << " " << AvgUninitVariablesPerFunction
2174 << " average variables per function.\n"
2175 << " " << MaxUninitAnalysisVariablesPerFunction
2176 << " max variables per function.\n"
2177 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2178 << " " << AvgUninitBlockVisitsPerFunction
2179 << " average block visits per function.\n"
2180 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2181 << " max block visits per function.\n";