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/ReachableCode.h"
29 #include "clang/Analysis/Analyses/ThreadSafety.h"
30 #include "clang/Analysis/Analyses/UninitializedValues.h"
31 #include "clang/Analysis/AnalysisContext.h"
32 #include "clang/Analysis/CFG.h"
33 #include "clang/Analysis/CFGStmtMap.h"
34 #include "clang/Basic/SourceLocation.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Lex/Lexer.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/FoldingSet.h"
43 #include "llvm/ADT/ImmutableMap.h"
44 #include "llvm/ADT/MapVector.h"
45 #include "llvm/ADT/PostOrderIterator.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/StringRef.h"
49 #include "llvm/Support/Casting.h"
55 using namespace clang;
57 //===----------------------------------------------------------------------===//
58 // Unreachable code analysis.
59 //===----------------------------------------------------------------------===//
62 class UnreachableCodeHandler : public reachable_code::Callback {
65 UnreachableCodeHandler(Sema &s) : S(s) {}
67 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
68 S.Diag(L, diag::warn_unreachable) << R1 << R2;
73 /// CheckUnreachable - Check for unreachable code.
74 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
75 UnreachableCodeHandler UC(S);
76 reachable_code::FindUnreachableCode(AC, UC);
79 //===----------------------------------------------------------------------===//
80 // Check for missing return value.
81 //===----------------------------------------------------------------------===//
83 enum ControlFlowKind {
88 NeverFallThroughOrReturn
91 /// CheckFallThrough - Check that we don't fall off the end of a
92 /// Statement that should return a value.
94 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
95 /// MaybeFallThrough iff we might or might not fall off the end,
96 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
97 /// return. We assume NeverFallThrough iff we never fall off the end of the
98 /// statement but we may return. We assume that functions not marked noreturn
100 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
101 CFG *cfg = AC.getCFG();
102 if (cfg == 0) return UnknownFallThrough;
104 // The CFG leaves in dead things, and we don't want the dead code paths to
105 // confuse us, so we mark all live things first.
106 llvm::BitVector live(cfg->getNumBlockIDs());
107 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
110 bool AddEHEdges = AC.getAddEHEdges();
111 if (!AddEHEdges && count != cfg->getNumBlockIDs())
112 // When there are things remaining dead, and we didn't add EH edges
113 // from CallExprs to the catch clauses, we have to go back and
114 // mark them as live.
115 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
117 if (!live[b.getBlockID()]) {
118 if (b.pred_begin() == b.pred_end()) {
119 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
120 // When not adding EH edges from calls, catch clauses
121 // can otherwise seem dead. Avoid noting them as dead.
122 count += reachable_code::ScanReachableFromBlock(&b, live);
128 // Now we know what is live, we check the live precessors of the exit block
129 // and look for fall through paths, being careful to ignore normal returns,
130 // and exceptional paths.
131 bool HasLiveReturn = false;
132 bool HasFakeEdge = false;
133 bool HasPlainEdge = false;
134 bool HasAbnormalEdge = false;
136 // Ignore default cases that aren't likely to be reachable because all
137 // enums in a switch(X) have explicit case statements.
138 CFGBlock::FilterOptions FO;
139 FO.IgnoreDefaultsWithCoveredEnums = 1;
141 for (CFGBlock::filtered_pred_iterator
142 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
143 const CFGBlock& B = **I;
144 if (!live[B.getBlockID()])
147 // Skip blocks which contain an element marked as no-return. They don't
148 // represent actually viable edges into the exit block, so mark them as
150 if (B.hasNoReturnElement()) {
151 HasAbnormalEdge = true;
155 // Destructors can appear after the 'return' in the CFG. This is
156 // normal. We need to look pass the destructors for the return
157 // statement (if it exists).
158 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
160 for ( ; ri != re ; ++ri)
161 if (ri->getAs<CFGStmt>())
164 // No more CFGElements in the block?
166 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
167 HasAbnormalEdge = true;
170 // A labeled empty statement, or the entry block...
175 CFGStmt CS = ri->castAs<CFGStmt>();
176 const Stmt *S = CS.getStmt();
177 if (isa<ReturnStmt>(S)) {
178 HasLiveReturn = true;
181 if (isa<ObjCAtThrowStmt>(S)) {
185 if (isa<CXXThrowExpr>(S)) {
189 if (isa<MSAsmStmt>(S)) {
190 // TODO: Verify this is correct.
192 HasLiveReturn = true;
195 if (isa<CXXTryStmt>(S)) {
196 HasAbnormalEdge = true;
199 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
201 HasAbnormalEdge = true;
209 return NeverFallThrough;
210 return NeverFallThroughOrReturn;
212 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
213 return MaybeFallThrough;
214 // This says AlwaysFallThrough for calls to functions that are not marked
215 // noreturn, that don't return. If people would like this warning to be more
216 // accurate, such functions should be marked as noreturn.
217 return AlwaysFallThrough;
222 struct CheckFallThroughDiagnostics {
223 unsigned diag_MaybeFallThrough_HasNoReturn;
224 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
225 unsigned diag_AlwaysFallThrough_HasNoReturn;
226 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
227 unsigned diag_NeverFallThroughOrReturn;
228 enum { Function, Block, Lambda } funMode;
229 SourceLocation FuncLoc;
231 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
232 CheckFallThroughDiagnostics D;
233 D.FuncLoc = Func->getLocation();
234 D.diag_MaybeFallThrough_HasNoReturn =
235 diag::warn_falloff_noreturn_function;
236 D.diag_MaybeFallThrough_ReturnsNonVoid =
237 diag::warn_maybe_falloff_nonvoid_function;
238 D.diag_AlwaysFallThrough_HasNoReturn =
239 diag::warn_falloff_noreturn_function;
240 D.diag_AlwaysFallThrough_ReturnsNonVoid =
241 diag::warn_falloff_nonvoid_function;
243 // Don't suggest that virtual functions be marked "noreturn", since they
244 // might be overridden by non-noreturn functions.
245 bool isVirtualMethod = false;
246 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
247 isVirtualMethod = Method->isVirtual();
249 // Don't suggest that template instantiations be marked "noreturn"
250 bool isTemplateInstantiation = false;
251 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
252 isTemplateInstantiation = Function->isTemplateInstantiation();
254 if (!isVirtualMethod && !isTemplateInstantiation)
255 D.diag_NeverFallThroughOrReturn =
256 diag::warn_suggest_noreturn_function;
258 D.diag_NeverFallThroughOrReturn = 0;
260 D.funMode = Function;
264 static CheckFallThroughDiagnostics MakeForBlock() {
265 CheckFallThroughDiagnostics D;
266 D.diag_MaybeFallThrough_HasNoReturn =
267 diag::err_noreturn_block_has_return_expr;
268 D.diag_MaybeFallThrough_ReturnsNonVoid =
269 diag::err_maybe_falloff_nonvoid_block;
270 D.diag_AlwaysFallThrough_HasNoReturn =
271 diag::err_noreturn_block_has_return_expr;
272 D.diag_AlwaysFallThrough_ReturnsNonVoid =
273 diag::err_falloff_nonvoid_block;
274 D.diag_NeverFallThroughOrReturn =
275 diag::warn_suggest_noreturn_block;
280 static CheckFallThroughDiagnostics MakeForLambda() {
281 CheckFallThroughDiagnostics D;
282 D.diag_MaybeFallThrough_HasNoReturn =
283 diag::err_noreturn_lambda_has_return_expr;
284 D.diag_MaybeFallThrough_ReturnsNonVoid =
285 diag::warn_maybe_falloff_nonvoid_lambda;
286 D.diag_AlwaysFallThrough_HasNoReturn =
287 diag::err_noreturn_lambda_has_return_expr;
288 D.diag_AlwaysFallThrough_ReturnsNonVoid =
289 diag::warn_falloff_nonvoid_lambda;
290 D.diag_NeverFallThroughOrReturn = 0;
295 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
296 bool HasNoReturn) const {
297 if (funMode == Function) {
298 return (ReturnsVoid ||
299 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
300 FuncLoc) == DiagnosticsEngine::Ignored)
302 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
303 FuncLoc) == DiagnosticsEngine::Ignored)
305 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
306 == DiagnosticsEngine::Ignored);
309 // For blocks / lambdas.
310 return ReturnsVoid && !HasNoReturn
311 && ((funMode == Lambda) ||
312 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
313 == DiagnosticsEngine::Ignored);
319 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
320 /// function that should return a value. Check that we don't fall off the end
321 /// of a noreturn function. We assume that functions and blocks not marked
322 /// noreturn will return.
323 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
324 const BlockExpr *blkExpr,
325 const CheckFallThroughDiagnostics& CD,
326 AnalysisDeclContext &AC) {
328 bool ReturnsVoid = false;
329 bool HasNoReturn = false;
331 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
332 ReturnsVoid = FD->getResultType()->isVoidType();
333 HasNoReturn = FD->isNoReturn();
335 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
336 ReturnsVoid = MD->getResultType()->isVoidType();
337 HasNoReturn = MD->hasAttr<NoReturnAttr>();
339 else if (isa<BlockDecl>(D)) {
340 QualType BlockTy = blkExpr->getType();
341 if (const FunctionType *FT =
342 BlockTy->getPointeeType()->getAs<FunctionType>()) {
343 if (FT->getResultType()->isVoidType())
345 if (FT->getNoReturnAttr())
350 DiagnosticsEngine &Diags = S.getDiagnostics();
352 // Short circuit for compilation speed.
353 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
356 // FIXME: Function try block
357 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
358 switch (CheckFallThrough(AC)) {
359 case UnknownFallThrough:
362 case MaybeFallThrough:
364 S.Diag(Compound->getRBracLoc(),
365 CD.diag_MaybeFallThrough_HasNoReturn);
366 else if (!ReturnsVoid)
367 S.Diag(Compound->getRBracLoc(),
368 CD.diag_MaybeFallThrough_ReturnsNonVoid);
370 case AlwaysFallThrough:
372 S.Diag(Compound->getRBracLoc(),
373 CD.diag_AlwaysFallThrough_HasNoReturn);
374 else if (!ReturnsVoid)
375 S.Diag(Compound->getRBracLoc(),
376 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
378 case NeverFallThroughOrReturn:
379 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
380 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
381 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
383 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
384 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
387 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
391 case NeverFallThrough:
397 //===----------------------------------------------------------------------===//
399 //===----------------------------------------------------------------------===//
402 /// ContainsReference - A visitor class to search for references to
403 /// a particular declaration (the needle) within any evaluated component of an
404 /// expression (recursively).
405 class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
407 const DeclRefExpr *Needle;
410 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
411 : EvaluatedExprVisitor<ContainsReference>(Context),
412 FoundReference(false), Needle(Needle) {}
414 void VisitExpr(Expr *E) {
415 // Stop evaluating if we already have a reference.
419 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
422 void VisitDeclRefExpr(DeclRefExpr *E) {
424 FoundReference = true;
426 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
429 bool doesContainReference() const { return FoundReference; }
433 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
434 QualType VariableTy = VD->getType().getCanonicalType();
435 if (VariableTy->isBlockPointerType() &&
436 !VD->hasAttr<BlocksAttr>()) {
437 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
438 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
442 // Don't issue a fixit if there is already an initializer.
446 // Suggest possible initialization (if any).
447 std::string Init = S.getFixItZeroInitializerForType(VariableTy);
451 // Don't suggest a fixit inside macros.
452 if (VD->getLocEnd().isMacroID())
455 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
457 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
458 << FixItHint::CreateInsertion(Loc, Init);
462 /// Create a fixit to remove an if-like statement, on the assumption that its
463 /// condition is CondVal.
464 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
465 const Stmt *Else, bool CondVal,
466 FixItHint &Fixit1, FixItHint &Fixit2) {
468 // If condition is always true, remove all but the 'then'.
469 Fixit1 = FixItHint::CreateRemoval(
470 CharSourceRange::getCharRange(If->getLocStart(),
471 Then->getLocStart()));
473 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
474 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
475 Fixit2 = FixItHint::CreateRemoval(
476 SourceRange(ElseKwLoc, Else->getLocEnd()));
479 // If condition is always false, remove all but the 'else'.
481 Fixit1 = FixItHint::CreateRemoval(
482 CharSourceRange::getCharRange(If->getLocStart(),
483 Else->getLocStart()));
485 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
489 /// DiagUninitUse -- Helper function to produce a diagnostic for an
490 /// uninitialized use of a variable.
491 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
492 bool IsCapturedByBlock) {
493 bool Diagnosed = false;
495 // Diagnose each branch which leads to a sometimes-uninitialized use.
496 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
498 assert(Use.getKind() == UninitUse::Sometimes);
500 const Expr *User = Use.getUser();
501 const Stmt *Term = I->Terminator;
503 // Information used when building the diagnostic.
508 // FixIts to suppress the diagnostic by removing the dead condition.
509 // For all binary terminators, branch 0 is taken if the condition is true,
510 // and branch 1 is taken if the condition is false.
511 int RemoveDiagKind = -1;
512 const char *FixitStr =
513 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
514 : (I->Output ? "1" : "0");
515 FixItHint Fixit1, Fixit2;
517 switch (Term->getStmtClass()) {
519 // Don't know how to report this. Just fall back to 'may be used
520 // uninitialized'. This happens for range-based for, which the user
521 // can't explicitly fix.
522 // FIXME: This also happens if the first use of a variable is always
523 // uninitialized, eg "for (int n; n < 10; ++n)". We should report that
524 // with the 'is uninitialized' diagnostic.
527 // "condition is true / condition is false".
528 case Stmt::IfStmtClass: {
529 const IfStmt *IS = cast<IfStmt>(Term);
532 Range = IS->getCond()->getSourceRange();
534 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
535 I->Output, Fixit1, Fixit2);
538 case Stmt::ConditionalOperatorClass: {
539 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
542 Range = CO->getCond()->getSourceRange();
544 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
545 I->Output, Fixit1, Fixit2);
548 case Stmt::BinaryOperatorClass: {
549 const BinaryOperator *BO = cast<BinaryOperator>(Term);
550 if (!BO->isLogicalOp())
553 Str = BO->getOpcodeStr();
554 Range = BO->getLHS()->getSourceRange();
556 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
557 (BO->getOpcode() == BO_LOr && !I->Output))
558 // true && y -> y, false || y -> y.
559 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
560 BO->getOperatorLoc()));
562 // false && y -> false, true || y -> true.
563 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
567 // "loop is entered / loop is exited".
568 case Stmt::WhileStmtClass:
571 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
573 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
575 case Stmt::ForStmtClass:
578 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
581 Fixit1 = FixItHint::CreateRemoval(Range);
583 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
586 // "condition is true / loop is exited".
587 case Stmt::DoStmtClass:
590 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
592 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
595 // "switch case is taken".
596 case Stmt::CaseStmtClass:
599 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
601 case Stmt::DefaultStmtClass:
604 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
608 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
609 << VD->getDeclName() << IsCapturedByBlock << DiagKind
610 << Str << I->Output << Range;
611 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
612 << IsCapturedByBlock << User->getSourceRange();
613 if (RemoveDiagKind != -1)
614 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
615 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
621 S.Diag(Use.getUser()->getLocStart(),
622 Use.getKind() == UninitUse::Always ? diag::warn_uninit_var
623 : diag::warn_maybe_uninit_var)
624 << VD->getDeclName() << IsCapturedByBlock
625 << Use.getUser()->getSourceRange();
628 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
629 /// uninitialized variable. This manages the different forms of diagnostic
630 /// emitted for particular types of uses. Returns true if the use was diagnosed
631 /// as a warning. If a particular use is one we omit warnings for, returns
633 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
634 const UninitUse &Use,
635 bool alwaysReportSelfInit = false) {
637 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
638 // Inspect the initializer of the variable declaration which is
639 // being referenced prior to its initialization. We emit
640 // specialized diagnostics for self-initialization, and we
641 // specifically avoid warning about self references which take the
646 // This is used to indicate to GCC that 'x' is intentionally left
647 // uninitialized. Proven code paths which access 'x' in
648 // an uninitialized state after this will still warn.
649 if (const Expr *Initializer = VD->getInit()) {
650 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
653 ContainsReference CR(S.Context, DRE);
654 CR.Visit(const_cast<Expr*>(Initializer));
655 if (CR.doesContainReference()) {
656 S.Diag(DRE->getLocStart(),
657 diag::warn_uninit_self_reference_in_init)
658 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
663 DiagUninitUse(S, VD, Use, false);
665 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
666 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
667 S.Diag(BE->getLocStart(),
668 diag::warn_uninit_byref_blockvar_captured_by_block)
669 << VD->getDeclName();
671 DiagUninitUse(S, VD, Use, true);
674 // Report where the variable was declared when the use wasn't within
675 // the initializer of that declaration & we didn't already suggest
676 // an initialization fixit.
677 if (!SuggestInitializationFixit(S, VD))
678 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
679 << VD->getDeclName();
685 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
687 FallthroughMapper(Sema &S)
688 : FoundSwitchStatements(false),
692 bool foundSwitchStatements() const { return FoundSwitchStatements; }
694 void markFallthroughVisited(const AttributedStmt *Stmt) {
695 bool Found = FallthroughStmts.erase(Stmt);
700 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
702 const AttrStmts &getFallthroughStmts() const {
703 return FallthroughStmts;
706 void fillReachableBlocks(CFG *Cfg) {
707 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
708 std::deque<const CFGBlock *> BlockQueue;
710 ReachableBlocks.insert(&Cfg->getEntry());
711 BlockQueue.push_back(&Cfg->getEntry());
712 // Mark all case blocks reachable to avoid problems with switching on
713 // constants, covered enums, etc.
714 // These blocks can contain fall-through annotations, and we don't want to
715 // issue a warn_fallthrough_attr_unreachable for them.
716 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
717 const CFGBlock *B = *I;
718 const Stmt *L = B->getLabel();
719 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
720 BlockQueue.push_back(B);
723 while (!BlockQueue.empty()) {
724 const CFGBlock *P = BlockQueue.front();
725 BlockQueue.pop_front();
726 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
729 if (*I && ReachableBlocks.insert(*I))
730 BlockQueue.push_back(*I);
735 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
736 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
738 int UnannotatedCnt = 0;
741 std::deque<const CFGBlock*> BlockQueue;
743 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
745 while (!BlockQueue.empty()) {
746 const CFGBlock *P = BlockQueue.front();
747 BlockQueue.pop_front();
749 const Stmt *Term = P->getTerminator();
750 if (Term && isa<SwitchStmt>(Term))
751 continue; // Switch statement, good.
753 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
754 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
755 continue; // Previous case label has no statements, good.
757 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
758 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
759 continue; // Case label is preceded with a normal label, good.
761 if (!ReachableBlocks.count(P)) {
762 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
764 ElemIt != ElemEnd; ++ElemIt) {
765 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
766 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
767 S.Diag(AS->getLocStart(),
768 diag::warn_fallthrough_attr_unreachable);
769 markFallthroughVisited(AS);
773 // Don't care about other unreachable statements.
776 // If there are no unreachable statements, this may be a special
779 // A a; // A has a destructor.
782 // // <<<< This place is represented by a 'hanging' CFG block.
787 const Stmt *LastStmt = getLastStmt(*P);
788 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
789 markFallthroughVisited(AS);
791 continue; // Fallthrough annotation, good.
794 if (!LastStmt) { // This block contains no executable statements.
795 // Traverse its predecessors.
796 std::copy(P->pred_begin(), P->pred_end(),
797 std::back_inserter(BlockQueue));
803 return !!UnannotatedCnt;
806 // RecursiveASTVisitor setup.
807 bool shouldWalkTypesOfTypeLocs() const { return false; }
809 bool VisitAttributedStmt(AttributedStmt *S) {
810 if (asFallThroughAttr(S))
811 FallthroughStmts.insert(S);
815 bool VisitSwitchStmt(SwitchStmt *S) {
816 FoundSwitchStatements = true;
820 // We don't want to traverse local type declarations. We analyze their
821 // methods separately.
822 bool TraverseDecl(Decl *D) { return true; }
826 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
827 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
828 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
834 static const Stmt *getLastStmt(const CFGBlock &B) {
835 if (const Stmt *Term = B.getTerminator())
837 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
839 ElemIt != ElemEnd; ++ElemIt) {
840 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
841 return CS->getStmt();
843 // Workaround to detect a statement thrown out by CFGBuilder:
844 // case X: {} case Y:
846 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
847 if (!isa<SwitchCase>(SW->getSubStmt()))
848 return SW->getSubStmt();
853 bool FoundSwitchStatements;
854 AttrStmts FallthroughStmts;
856 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
860 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
862 // Only perform this analysis when using C++11. There is no good workflow
863 // for this warning when not using C++11. There is no good way to silence
864 // the warning (no attribute is available) unless we are using C++11's support
865 // for generalized attributes. Once could use pragmas to silence the warning,
866 // but as a general solution that is gross and not in the spirit of this
869 // NOTE: This an intermediate solution. There are on-going discussions on
870 // how to properly support this warning outside of C++11 with an annotation.
871 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
874 FallthroughMapper FM(S);
875 FM.TraverseStmt(AC.getBody());
877 if (!FM.foundSwitchStatements())
880 if (PerFunction && FM.getFallthroughStmts().empty())
883 CFG *Cfg = AC.getCFG();
888 FM.fillReachableBlocks(Cfg);
890 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
891 const CFGBlock *B = *I;
892 const Stmt *Label = B->getLabel();
894 if (!Label || !isa<SwitchCase>(Label))
899 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
902 S.Diag(Label->getLocStart(),
903 PerFunction ? diag::warn_unannotated_fallthrough_per_function
904 : diag::warn_unannotated_fallthrough);
907 SourceLocation L = Label->getLocStart();
910 if (S.getLangOpts().CPlusPlus11) {
911 const Stmt *Term = B->getTerminator();
913 while (B->empty() && !Term && B->succ_size() == 1) {
914 B = *B->succ_begin();
915 Term = B->getTerminator();
917 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
918 Preprocessor &PP = S.getPreprocessor();
919 TokenValue Tokens[] = {
920 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
921 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
922 tok::r_square, tok::r_square
924 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
925 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
926 if (!MacroName.empty())
927 AnnotationSpelling = MacroName;
928 SmallString<64> TextToInsert(AnnotationSpelling);
929 TextToInsert += "; ";
930 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
931 AnnotationSpelling <<
932 FixItHint::CreateInsertion(L, TextToInsert);
935 S.Diag(L, diag::note_insert_break_fixit) <<
936 FixItHint::CreateInsertion(L, "break; ");
940 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
941 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
942 E = Fallthroughs.end();
944 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
950 typedef std::pair<const Stmt *,
951 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
954 class StmtUseSorter {
955 const SourceManager &SM;
958 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
960 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
961 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
962 RHS.first->getLocStart());
967 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
972 switch (S->getStmtClass()) {
973 case Stmt::ForStmtClass:
974 case Stmt::WhileStmtClass:
975 case Stmt::CXXForRangeStmtClass:
976 case Stmt::ObjCForCollectionStmtClass:
978 case Stmt::DoStmtClass: {
979 const Expr *Cond = cast<DoStmt>(S)->getCond();
981 if (!Cond->EvaluateAsInt(Val, Ctx))
983 return Val.getBoolValue();
988 } while ((S = PM.getParent(S)));
994 static void diagnoseRepeatedUseOfWeak(Sema &S,
995 const sema::FunctionScopeInfo *CurFn,
997 const ParentMap &PM) {
998 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
999 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1000 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1002 ASTContext &Ctx = S.getASTContext();
1004 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1006 // Extract all weak objects that are referenced more than once.
1007 SmallVector<StmtUsesPair, 8> UsesByStmt;
1008 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1010 const WeakUseVector &Uses = I->second;
1012 // Find the first read of the weak object.
1013 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1014 for ( ; UI != UE; ++UI) {
1019 // If there were only writes to this object, don't warn.
1023 // If there was only one read, followed by any number of writes, and the
1024 // read is not within a loop, don't warn. Additionally, don't warn in a
1025 // loop if the base object is a local variable -- local variables are often
1026 // changed in loops.
1027 if (UI == Uses.begin()) {
1028 WeakUseVector::const_iterator UI2 = UI;
1029 for (++UI2; UI2 != UE; ++UI2)
1030 if (UI2->isUnsafe())
1034 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1037 const WeakObjectProfileTy &Profile = I->first;
1038 if (!Profile.isExactProfile())
1041 const NamedDecl *Base = Profile.getBase();
1043 Base = Profile.getProperty();
1044 assert(Base && "A profile always has a base or property.");
1046 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1047 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1052 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1055 if (UsesByStmt.empty())
1058 // Sort by first use so that we emit the warnings in a deterministic order.
1059 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1060 StmtUseSorter(S.getSourceManager()));
1062 // Classify the current code body for better warning text.
1063 // This enum should stay in sync with the cases in
1064 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1065 // FIXME: Should we use a common classification enum and the same set of
1066 // possibilities all throughout Sema?
1074 if (isa<sema::BlockScopeInfo>(CurFn))
1075 FunctionKind = Block;
1076 else if (isa<sema::LambdaScopeInfo>(CurFn))
1077 FunctionKind = Lambda;
1078 else if (isa<ObjCMethodDecl>(D))
1079 FunctionKind = Method;
1081 FunctionKind = Function;
1083 // Iterate through the sorted problems and emit warnings for each.
1084 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1085 E = UsesByStmt.end();
1087 const Stmt *FirstRead = I->first;
1088 const WeakObjectProfileTy &Key = I->second->first;
1089 const WeakUseVector &Uses = I->second->second;
1091 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1092 // may not contain enough information to determine that these are different
1093 // properties. We can only be 100% sure of a repeated use in certain cases,
1094 // and we adjust the diagnostic kind accordingly so that the less certain
1095 // case can be turned off if it is too noisy.
1097 if (Key.isExactProfile())
1098 DiagKind = diag::warn_arc_repeated_use_of_weak;
1100 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1102 // Classify the weak object being accessed for better warning text.
1103 // This enum should stay in sync with the cases in
1104 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1112 const NamedDecl *D = Key.getProperty();
1113 if (isa<VarDecl>(D))
1114 ObjectKind = Variable;
1115 else if (isa<ObjCPropertyDecl>(D))
1116 ObjectKind = Property;
1117 else if (isa<ObjCMethodDecl>(D))
1118 ObjectKind = ImplicitProperty;
1119 else if (isa<ObjCIvarDecl>(D))
1122 llvm_unreachable("Unexpected weak object kind!");
1124 // Show the first time the object was read.
1125 S.Diag(FirstRead->getLocStart(), DiagKind)
1126 << ObjectKind << D << FunctionKind
1127 << FirstRead->getSourceRange();
1129 // Print all the other accesses as notes.
1130 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1132 if (UI->getUseExpr() == FirstRead)
1134 S.Diag(UI->getUseExpr()->getLocStart(),
1135 diag::note_arc_weak_also_accessed_here)
1136 << UI->getUseExpr()->getSourceRange();
1144 bool operator()(const UninitUse &a, const UninitUse &b) {
1145 // Prefer a more confident report over a less confident one.
1146 if (a.getKind() != b.getKind())
1147 return a.getKind() > b.getKind();
1148 SourceLocation aLoc = a.getUser()->getLocStart();
1149 SourceLocation bLoc = b.getUser()->getLocStart();
1150 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1154 class UninitValsDiagReporter : public UninitVariablesHandler {
1156 typedef SmallVector<UninitUse, 2> UsesVec;
1157 typedef std::pair<UsesVec*, bool> MappedType;
1158 // Prefer using MapVector to DenseMap, so that iteration order will be
1159 // the same as insertion order. This is needed to obtain a deterministic
1160 // order of diagnostics when calling flushDiagnostics().
1161 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1165 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1166 ~UninitValsDiagReporter() {
1170 MappedType &getUses(const VarDecl *vd) {
1172 uses = new UsesMap();
1174 MappedType &V = (*uses)[vd];
1175 UsesVec *&vec = V.first;
1177 vec = new UsesVec();
1182 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
1183 getUses(vd).first->push_back(use);
1186 void handleSelfInit(const VarDecl *vd) {
1187 getUses(vd).second = true;
1190 void flushDiagnostics() {
1194 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1195 const VarDecl *vd = i->first;
1196 const MappedType &V = i->second;
1198 UsesVec *vec = V.first;
1199 bool hasSelfInit = V.second;
1201 // Specially handle the case where we have uses of an uninitialized
1202 // variable, but the root cause is an idiomatic self-init. We want
1203 // to report the diagnostic at the self-init since that is the root cause.
1204 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1205 DiagnoseUninitializedUse(S, vd,
1206 UninitUse(vd->getInit()->IgnoreParenCasts(),
1207 /* isAlwaysUninit */ true),
1208 /* alwaysReportSelfInit */ true);
1210 // Sort the uses by their SourceLocations. While not strictly
1211 // guaranteed to produce them in line/column order, this will provide
1212 // a stable ordering.
1213 std::sort(vec->begin(), vec->end(), SLocSort());
1215 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1217 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1218 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1220 if (DiagnoseUninitializedUse(S, vd, Use))
1221 // Skip further diagnostics for this variable. We try to warn only
1222 // on the first point at which a variable is used uninitialized.
1227 // Release the uses vector.
1234 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1235 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
1236 if (i->getKind() == UninitUse::Always) {
1246 //===----------------------------------------------------------------------===//
1248 //===----------------------------------------------------------------------===//
1250 namespace thread_safety {
1251 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1252 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1253 typedef std::list<DelayedDiag> DiagList;
1255 struct SortDiagBySourceLocation {
1257 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1259 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1260 // Although this call will be slow, this is only called when outputting
1261 // multiple warnings.
1262 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1267 class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1270 SourceLocation FunLocation, FunEndLocation;
1273 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
1274 // Gracefully handle rare cases when the analysis can't get a more
1275 // precise source location.
1278 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1279 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1283 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1284 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
1286 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1287 /// We need to output diagnostics produced while iterating through
1288 /// the lockset in deterministic order, so this function orders diagnostics
1289 /// and outputs them.
1290 void emitDiagnostics() {
1291 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1292 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1294 S.Diag(I->first.first, I->first.second);
1295 const OptionalNotes &Notes = I->second;
1296 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1297 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1301 void handleInvalidLockExp(SourceLocation Loc) {
1302 PartialDiagnosticAt Warning(Loc,
1303 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1304 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1306 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1307 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1310 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1311 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1314 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1315 SourceLocation LocEndOfScope,
1317 unsigned DiagID = 0;
1319 case LEK_LockedSomePredecessors:
1320 DiagID = diag::warn_lock_some_predecessors;
1322 case LEK_LockedSomeLoopIterations:
1323 DiagID = diag::warn_expecting_lock_held_on_loop;
1325 case LEK_LockedAtEndOfFunction:
1326 DiagID = diag::warn_no_unlock;
1328 case LEK_NotLockedAtEndOfFunction:
1329 DiagID = diag::warn_expecting_locked;
1332 if (LocEndOfScope.isInvalid())
1333 LocEndOfScope = FunEndLocation;
1335 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
1336 if (LocLocked.isValid()) {
1337 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1338 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1341 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1345 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1346 SourceLocation Loc2) {
1347 PartialDiagnosticAt Warning(
1348 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1349 PartialDiagnosticAt Note(
1350 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1351 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1354 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1355 AccessKind AK, SourceLocation Loc) {
1356 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1357 && "Only works for variables");
1358 unsigned DiagID = POK == POK_VarAccess?
1359 diag::warn_variable_requires_any_lock:
1360 diag::warn_var_deref_requires_any_lock;
1361 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1362 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1363 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1366 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
1367 Name LockName, LockKind LK, SourceLocation Loc,
1368 Name *PossibleMatch) {
1369 unsigned DiagID = 0;
1370 if (PossibleMatch) {
1373 DiagID = diag::warn_variable_requires_lock_precise;
1375 case POK_VarDereference:
1376 DiagID = diag::warn_var_deref_requires_lock_precise;
1378 case POK_FunctionCall:
1379 DiagID = diag::warn_fun_requires_lock_precise;
1382 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1383 << D->getNameAsString() << LockName << LK);
1384 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1386 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1390 DiagID = diag::warn_variable_requires_lock;
1392 case POK_VarDereference:
1393 DiagID = diag::warn_var_deref_requires_lock;
1395 case POK_FunctionCall:
1396 DiagID = diag::warn_fun_requires_lock;
1399 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1400 << D->getNameAsString() << LockName << LK);
1401 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1405 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
1406 PartialDiagnosticAt Warning(Loc,
1407 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1408 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1415 //===----------------------------------------------------------------------===//
1416 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1417 // warnings on a function, method, or block.
1418 //===----------------------------------------------------------------------===//
1420 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1421 enableCheckFallThrough = 1;
1422 enableCheckUnreachable = 0;
1423 enableThreadSafetyAnalysis = 0;
1426 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1428 NumFunctionsAnalyzed(0),
1429 NumFunctionsWithBadCFGs(0),
1431 MaxCFGBlocksPerFunction(0),
1432 NumUninitAnalysisFunctions(0),
1433 NumUninitAnalysisVariables(0),
1434 MaxUninitAnalysisVariablesPerFunction(0),
1435 NumUninitAnalysisBlockVisits(0),
1436 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1437 DiagnosticsEngine &D = S.getDiagnostics();
1438 DefaultPolicy.enableCheckUnreachable = (unsigned)
1439 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
1440 DiagnosticsEngine::Ignored);
1441 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1442 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
1443 DiagnosticsEngine::Ignored);
1447 static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
1448 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1449 i = fscope->PossiblyUnreachableDiags.begin(),
1450 e = fscope->PossiblyUnreachableDiags.end();
1452 const sema::PossiblyUnreachableDiag &D = *i;
1453 S.Diag(D.Loc, D.PD);
1458 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1459 sema::FunctionScopeInfo *fscope,
1460 const Decl *D, const BlockExpr *blkExpr) {
1462 // We avoid doing analysis-based warnings when there are errors for
1464 // (1) The CFGs often can't be constructed (if the body is invalid), so
1465 // don't bother trying.
1466 // (2) The code already has problems; running the analysis just takes more
1468 DiagnosticsEngine &Diags = S.getDiagnostics();
1470 // Do not do any analysis for declarations in system headers if we are
1471 // going to just ignore them.
1472 if (Diags.getSuppressSystemWarnings() &&
1473 S.SourceMgr.isInSystemHeader(D->getLocation()))
1476 // For code in dependent contexts, we'll do this at instantiation time.
1477 if (cast<DeclContext>(D)->isDependentContext())
1480 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1481 // Flush out any possibly unreachable diagnostics.
1482 flushDiagnostics(S, fscope);
1486 const Stmt *Body = D->getBody();
1489 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
1491 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1492 // explosion for destrutors that can result and the compile time hit.
1493 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1494 AC.getCFGBuildOptions().AddEHEdges = false;
1495 AC.getCFGBuildOptions().AddInitializers = true;
1496 AC.getCFGBuildOptions().AddImplicitDtors = true;
1497 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1499 // Force that certain expressions appear as CFGElements in the CFG. This
1500 // is used to speed up various analyses.
1501 // FIXME: This isn't the right factoring. This is here for initial
1502 // prototyping, but we need a way for analyses to say what expressions they
1503 // expect to always be CFGElements and then fill in the BuildOptions
1504 // appropriately. This is essentially a layering violation.
1505 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
1506 // Unreachable code analysis and thread safety require a linearized CFG.
1507 AC.getCFGBuildOptions().setAllAlwaysAdd();
1510 AC.getCFGBuildOptions()
1511 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1512 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1513 .setAlwaysAdd(Stmt::BlockExprClass)
1514 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1515 .setAlwaysAdd(Stmt::DeclRefExprClass)
1516 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1517 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1518 .setAlwaysAdd(Stmt::AttributedStmtClass);
1521 // Construct the analysis context with the specified CFG build options.
1523 // Emit delayed diagnostics.
1524 if (!fscope->PossiblyUnreachableDiags.empty()) {
1525 bool analyzed = false;
1527 // Register the expressions with the CFGBuilder.
1528 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1529 i = fscope->PossiblyUnreachableDiags.begin(),
1530 e = fscope->PossiblyUnreachableDiags.end();
1532 if (const Stmt *stmt = i->stmt)
1533 AC.registerForcedBlockExpression(stmt);
1538 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1539 i = fscope->PossiblyUnreachableDiags.begin(),
1540 e = fscope->PossiblyUnreachableDiags.end();
1543 const sema::PossiblyUnreachableDiag &D = *i;
1544 bool processed = false;
1545 if (const Stmt *stmt = i->stmt) {
1546 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
1547 CFGReverseBlockReachabilityAnalysis *cra =
1548 AC.getCFGReachablityAnalysis();
1549 // FIXME: We should be able to assert that block is non-null, but
1550 // the CFG analysis can skip potentially-evaluated expressions in
1551 // edge cases; see test/Sema/vla-2.c.
1553 // Can this block be reached from the entrance?
1554 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
1555 S.Diag(D.Loc, D.PD);
1560 // Emit the warning anyway if we cannot map to a basic block.
1561 S.Diag(D.Loc, D.PD);
1567 flushDiagnostics(S, fscope);
1571 // Warning: check missing 'return'
1572 if (P.enableCheckFallThrough) {
1573 const CheckFallThroughDiagnostics &CD =
1574 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
1575 : (isa<CXXMethodDecl>(D) &&
1576 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1577 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1578 ? CheckFallThroughDiagnostics::MakeForLambda()
1579 : CheckFallThroughDiagnostics::MakeForFunction(D));
1580 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
1583 // Warning: check for unreachable code
1584 if (P.enableCheckUnreachable) {
1585 // Only check for unreachable code on non-template instantiations.
1586 // Different template instantiations can effectively change the control-flow
1587 // and it is very difficult to prove that a snippet of code in a template
1588 // is unreachable for all instantiations.
1589 bool isTemplateInstantiation = false;
1590 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1591 isTemplateInstantiation = Function->isTemplateInstantiation();
1592 if (!isTemplateInstantiation)
1593 CheckUnreachable(S, AC);
1596 // Check for thread safety violations
1597 if (P.enableThreadSafetyAnalysis) {
1598 SourceLocation FL = AC.getDecl()->getLocation();
1599 SourceLocation FEL = AC.getDecl()->getLocEnd();
1600 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
1601 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1602 != DiagnosticsEngine::Ignored)
1603 Reporter.setIssueBetaWarnings(true);
1605 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1606 Reporter.emitDiagnostics();
1609 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
1610 != DiagnosticsEngine::Ignored ||
1611 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1612 != DiagnosticsEngine::Ignored ||
1613 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
1614 != DiagnosticsEngine::Ignored) {
1615 if (CFG *cfg = AC.getCFG()) {
1616 UninitValsDiagReporter reporter(S);
1617 UninitVariablesAnalysisStats stats;
1618 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
1619 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
1622 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1623 ++NumUninitAnalysisFunctions;
1624 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1625 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1626 MaxUninitAnalysisVariablesPerFunction =
1627 std::max(MaxUninitAnalysisVariablesPerFunction,
1628 stats.NumVariablesAnalyzed);
1629 MaxUninitAnalysisBlockVisitsPerFunction =
1630 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1631 stats.NumBlockVisits);
1636 bool FallThroughDiagFull =
1637 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1638 D->getLocStart()) != DiagnosticsEngine::Ignored;
1639 bool FallThroughDiagPerFunction =
1640 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
1641 D->getLocStart()) != DiagnosticsEngine::Ignored;
1642 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
1643 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
1646 if (S.getLangOpts().ObjCARCWeak &&
1647 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1648 D->getLocStart()) != DiagnosticsEngine::Ignored)
1649 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
1651 // Collect statistics about the CFG if it was built.
1652 if (S.CollectStats && AC.isCFGBuilt()) {
1653 ++NumFunctionsAnalyzed;
1654 if (CFG *cfg = AC.getCFG()) {
1655 // If we successfully built a CFG for this context, record some more
1656 // detail information about it.
1657 NumCFGBlocks += cfg->getNumBlockIDs();
1658 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
1659 cfg->getNumBlockIDs());
1661 ++NumFunctionsWithBadCFGs;
1666 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1667 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1669 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1670 unsigned AvgCFGBlocksPerFunction =
1671 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1672 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1673 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1674 << " " << NumCFGBlocks << " CFG blocks built.\n"
1675 << " " << AvgCFGBlocksPerFunction
1676 << " average CFG blocks per function.\n"
1677 << " " << MaxCFGBlocksPerFunction
1678 << " max CFG blocks per function.\n";
1680 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1681 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1682 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1683 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1684 llvm::errs() << NumUninitAnalysisFunctions
1685 << " functions analyzed for uninitialiazed variables\n"
1686 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1687 << " " << AvgUninitVariablesPerFunction
1688 << " average variables per function.\n"
1689 << " " << MaxUninitAnalysisVariablesPerFunction
1690 << " max variables per function.\n"
1691 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1692 << " " << AvgUninitBlockVisitsPerFunction
1693 << " average block visits per function.\n"
1694 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1695 << " max block visits per function.\n";