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/Sema/SemaInternal.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Lex/Lexer.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/EvaluatedExprVisitor.h"
30 #include "clang/AST/ParentMap.h"
31 #include "clang/AST/StmtVisitor.h"
32 #include "clang/AST/RecursiveASTVisitor.h"
33 #include "clang/Analysis/AnalysisContext.h"
34 #include "clang/Analysis/CFG.h"
35 #include "clang/Analysis/Analyses/ReachableCode.h"
36 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
37 #include "clang/Analysis/Analyses/ThreadSafety.h"
38 #include "clang/Analysis/CFGStmtMap.h"
39 #include "clang/Analysis/Analyses/UninitializedValues.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/PostOrderIterator.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/StringRef.h"
48 #include "llvm/Support/Casting.h"
54 using namespace clang;
56 //===----------------------------------------------------------------------===//
57 // Unreachable code analysis.
58 //===----------------------------------------------------------------------===//
61 class UnreachableCodeHandler : public reachable_code::Callback {
64 UnreachableCodeHandler(Sema &s) : S(s) {}
66 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
67 S.Diag(L, diag::warn_unreachable) << R1 << R2;
72 /// CheckUnreachable - Check for unreachable code.
73 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
74 UnreachableCodeHandler UC(S);
75 reachable_code::FindUnreachableCode(AC, UC);
78 //===----------------------------------------------------------------------===//
79 // Check for missing return value.
80 //===----------------------------------------------------------------------===//
82 enum ControlFlowKind {
87 NeverFallThroughOrReturn
90 /// CheckFallThrough - Check that we don't fall off the end of a
91 /// Statement that should return a value.
93 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
94 /// MaybeFallThrough iff we might or might not fall off the end,
95 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
96 /// return. We assume NeverFallThrough iff we never fall off the end of the
97 /// statement but we may return. We assume that functions not marked noreturn
99 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
100 CFG *cfg = AC.getCFG();
101 if (cfg == 0) return UnknownFallThrough;
103 // The CFG leaves in dead things, and we don't want the dead code paths to
104 // confuse us, so we mark all live things first.
105 llvm::BitVector live(cfg->getNumBlockIDs());
106 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
109 bool AddEHEdges = AC.getAddEHEdges();
110 if (!AddEHEdges && count != cfg->getNumBlockIDs())
111 // When there are things remaining dead, and we didn't add EH edges
112 // from CallExprs to the catch clauses, we have to go back and
113 // mark them as live.
114 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
116 if (!live[b.getBlockID()]) {
117 if (b.pred_begin() == b.pred_end()) {
118 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
119 // When not adding EH edges from calls, catch clauses
120 // can otherwise seem dead. Avoid noting them as dead.
121 count += reachable_code::ScanReachableFromBlock(&b, live);
127 // Now we know what is live, we check the live precessors of the exit block
128 // and look for fall through paths, being careful to ignore normal returns,
129 // and exceptional paths.
130 bool HasLiveReturn = false;
131 bool HasFakeEdge = false;
132 bool HasPlainEdge = false;
133 bool HasAbnormalEdge = false;
135 // Ignore default cases that aren't likely to be reachable because all
136 // enums in a switch(X) have explicit case statements.
137 CFGBlock::FilterOptions FO;
138 FO.IgnoreDefaultsWithCoveredEnums = 1;
140 for (CFGBlock::filtered_pred_iterator
141 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
142 const CFGBlock& B = **I;
143 if (!live[B.getBlockID()])
146 // Skip blocks which contain an element marked as no-return. They don't
147 // represent actually viable edges into the exit block, so mark them as
149 if (B.hasNoReturnElement()) {
150 HasAbnormalEdge = true;
154 // Destructors can appear after the 'return' in the CFG. This is
155 // normal. We need to look pass the destructors for the return
156 // statement (if it exists).
157 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
159 for ( ; ri != re ; ++ri)
160 if (isa<CFGStmt>(*ri))
163 // No more CFGElements in the block?
165 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
166 HasAbnormalEdge = true;
169 // A labeled empty statement, or the entry block...
174 CFGStmt CS = cast<CFGStmt>(*ri);
175 const Stmt *S = CS.getStmt();
176 if (isa<ReturnStmt>(S)) {
177 HasLiveReturn = true;
180 if (isa<ObjCAtThrowStmt>(S)) {
184 if (isa<CXXThrowExpr>(S)) {
188 if (isa<MSAsmStmt>(S)) {
189 // TODO: Verify this is correct.
191 HasLiveReturn = true;
194 if (isa<CXXTryStmt>(S)) {
195 HasAbnormalEdge = true;
198 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
200 HasAbnormalEdge = true;
208 return NeverFallThrough;
209 return NeverFallThroughOrReturn;
211 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
212 return MaybeFallThrough;
213 // This says AlwaysFallThrough for calls to functions that are not marked
214 // noreturn, that don't return. If people would like this warning to be more
215 // accurate, such functions should be marked as noreturn.
216 return AlwaysFallThrough;
221 struct CheckFallThroughDiagnostics {
222 unsigned diag_MaybeFallThrough_HasNoReturn;
223 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
224 unsigned diag_AlwaysFallThrough_HasNoReturn;
225 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
226 unsigned diag_NeverFallThroughOrReturn;
227 enum { Function, Block, Lambda } funMode;
228 SourceLocation FuncLoc;
230 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
231 CheckFallThroughDiagnostics D;
232 D.FuncLoc = Func->getLocation();
233 D.diag_MaybeFallThrough_HasNoReturn =
234 diag::warn_falloff_noreturn_function;
235 D.diag_MaybeFallThrough_ReturnsNonVoid =
236 diag::warn_maybe_falloff_nonvoid_function;
237 D.diag_AlwaysFallThrough_HasNoReturn =
238 diag::warn_falloff_noreturn_function;
239 D.diag_AlwaysFallThrough_ReturnsNonVoid =
240 diag::warn_falloff_nonvoid_function;
242 // Don't suggest that virtual functions be marked "noreturn", since they
243 // might be overridden by non-noreturn functions.
244 bool isVirtualMethod = false;
245 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
246 isVirtualMethod = Method->isVirtual();
248 // Don't suggest that template instantiations be marked "noreturn"
249 bool isTemplateInstantiation = false;
250 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
251 isTemplateInstantiation = Function->isTemplateInstantiation();
253 if (!isVirtualMethod && !isTemplateInstantiation)
254 D.diag_NeverFallThroughOrReturn =
255 diag::warn_suggest_noreturn_function;
257 D.diag_NeverFallThroughOrReturn = 0;
259 D.funMode = Function;
263 static CheckFallThroughDiagnostics MakeForBlock() {
264 CheckFallThroughDiagnostics D;
265 D.diag_MaybeFallThrough_HasNoReturn =
266 diag::err_noreturn_block_has_return_expr;
267 D.diag_MaybeFallThrough_ReturnsNonVoid =
268 diag::err_maybe_falloff_nonvoid_block;
269 D.diag_AlwaysFallThrough_HasNoReturn =
270 diag::err_noreturn_block_has_return_expr;
271 D.diag_AlwaysFallThrough_ReturnsNonVoid =
272 diag::err_falloff_nonvoid_block;
273 D.diag_NeverFallThroughOrReturn =
274 diag::warn_suggest_noreturn_block;
279 static CheckFallThroughDiagnostics MakeForLambda() {
280 CheckFallThroughDiagnostics D;
281 D.diag_MaybeFallThrough_HasNoReturn =
282 diag::err_noreturn_lambda_has_return_expr;
283 D.diag_MaybeFallThrough_ReturnsNonVoid =
284 diag::warn_maybe_falloff_nonvoid_lambda;
285 D.diag_AlwaysFallThrough_HasNoReturn =
286 diag::err_noreturn_lambda_has_return_expr;
287 D.diag_AlwaysFallThrough_ReturnsNonVoid =
288 diag::warn_falloff_nonvoid_lambda;
289 D.diag_NeverFallThroughOrReturn = 0;
294 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
295 bool HasNoReturn) const {
296 if (funMode == Function) {
297 return (ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
299 FuncLoc) == DiagnosticsEngine::Ignored)
301 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
302 FuncLoc) == DiagnosticsEngine::Ignored)
304 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
305 == DiagnosticsEngine::Ignored);
308 // For blocks / lambdas.
309 return ReturnsVoid && !HasNoReturn
310 && ((funMode == Lambda) ||
311 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
312 == DiagnosticsEngine::Ignored);
318 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
319 /// function that should return a value. Check that we don't fall off the end
320 /// of a noreturn function. We assume that functions and blocks not marked
321 /// noreturn will return.
322 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
323 const BlockExpr *blkExpr,
324 const CheckFallThroughDiagnostics& CD,
325 AnalysisDeclContext &AC) {
327 bool ReturnsVoid = false;
328 bool HasNoReturn = false;
330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
331 ReturnsVoid = FD->getResultType()->isVoidType();
332 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
333 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
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 diagnosic 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 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
707 int UnannotatedCnt = 0;
710 std::deque<const CFGBlock*> BlockQueue;
712 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
714 while (!BlockQueue.empty()) {
715 const CFGBlock *P = BlockQueue.front();
716 BlockQueue.pop_front();
718 const Stmt *Term = P->getTerminator();
719 if (Term && isa<SwitchStmt>(Term))
720 continue; // Switch statement, good.
722 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
723 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
724 continue; // Previous case label has no statements, good.
726 if (P->pred_begin() == P->pred_end()) { // The block is unreachable.
727 // This only catches trivially unreachable blocks.
728 for (CFGBlock::const_iterator ElIt = P->begin(), ElEnd = P->end();
729 ElIt != ElEnd; ++ElIt) {
730 if (const CFGStmt *CS = ElIt->getAs<CFGStmt>()){
731 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
732 S.Diag(AS->getLocStart(),
733 diag::warn_fallthrough_attr_unreachable);
734 markFallthroughVisited(AS);
737 // Don't care about other unreachable statements.
740 // If there are no unreachable statements, this may be a special
743 // A a; // A has a destructor.
746 // // <<<< This place is represented by a 'hanging' CFG block.
751 const Stmt *LastStmt = getLastStmt(*P);
752 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
753 markFallthroughVisited(AS);
755 continue; // Fallthrough annotation, good.
758 if (!LastStmt) { // This block contains no executable statements.
759 // Traverse its predecessors.
760 std::copy(P->pred_begin(), P->pred_end(),
761 std::back_inserter(BlockQueue));
767 return !!UnannotatedCnt;
770 // RecursiveASTVisitor setup.
771 bool shouldWalkTypesOfTypeLocs() const { return false; }
773 bool VisitAttributedStmt(AttributedStmt *S) {
774 if (asFallThroughAttr(S))
775 FallthroughStmts.insert(S);
779 bool VisitSwitchStmt(SwitchStmt *S) {
780 FoundSwitchStatements = true;
786 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
787 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
788 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
794 static const Stmt *getLastStmt(const CFGBlock &B) {
795 if (const Stmt *Term = B.getTerminator())
797 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
799 ElemIt != ElemEnd; ++ElemIt) {
800 if (const CFGStmt *CS = ElemIt->getAs<CFGStmt>())
801 return CS->getStmt();
803 // Workaround to detect a statement thrown out by CFGBuilder:
804 // case X: {} case Y:
806 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
807 if (!isa<SwitchCase>(SW->getSubStmt()))
808 return SW->getSubStmt();
813 bool FoundSwitchStatements;
814 AttrStmts FallthroughStmts;
819 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
821 // Only perform this analysis when using C++11. There is no good workflow
822 // for this warning when not using C++11. There is no good way to silence
823 // the warning (no attribute is available) unless we are using C++11's support
824 // for generalized attributes. Once could use pragmas to silence the warning,
825 // but as a general solution that is gross and not in the spirit of this
828 // NOTE: This an intermediate solution. There are on-going discussions on
829 // how to properly support this warning outside of C++11 with an annotation.
830 if (!AC.getASTContext().getLangOpts().CPlusPlus0x)
833 FallthroughMapper FM(S);
834 FM.TraverseStmt(AC.getBody());
836 if (!FM.foundSwitchStatements())
839 if (PerFunction && FM.getFallthroughStmts().empty())
842 CFG *Cfg = AC.getCFG();
849 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
850 const CFGBlock &B = **I;
851 const Stmt *Label = B.getLabel();
853 if (!Label || !isa<SwitchCase>(Label))
856 if (!FM.checkFallThroughIntoBlock(B, AnnotatedCnt))
859 S.Diag(Label->getLocStart(),
860 PerFunction ? diag::warn_unannotated_fallthrough_per_function
861 : diag::warn_unannotated_fallthrough);
864 SourceLocation L = Label->getLocStart();
867 if (S.getLangOpts().CPlusPlus0x) {
868 const Stmt *Term = B.getTerminator();
869 if (!(B.empty() && Term && isa<BreakStmt>(Term))) {
870 Preprocessor &PP = S.getPreprocessor();
871 TokenValue Tokens[] = {
872 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
873 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
874 tok::r_square, tok::r_square
876 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
877 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
878 if (!MacroName.empty())
879 AnnotationSpelling = MacroName;
880 SmallString<64> TextToInsert(AnnotationSpelling);
881 TextToInsert += "; ";
882 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
883 AnnotationSpelling <<
884 FixItHint::CreateInsertion(L, TextToInsert);
887 S.Diag(L, diag::note_insert_break_fixit) <<
888 FixItHint::CreateInsertion(L, "break; ");
892 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
893 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
894 E = Fallthroughs.end();
896 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
902 typedef std::pair<const Stmt *,
903 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
906 class StmtUseSorter {
907 const SourceManager &SM;
910 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
912 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
913 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
914 RHS.first->getLocStart());
919 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
924 switch (S->getStmtClass()) {
925 case Stmt::ForStmtClass:
926 case Stmt::WhileStmtClass:
927 case Stmt::CXXForRangeStmtClass:
928 case Stmt::ObjCForCollectionStmtClass:
930 case Stmt::DoStmtClass: {
931 const Expr *Cond = cast<DoStmt>(S)->getCond();
933 if (!Cond->EvaluateAsInt(Val, Ctx))
935 return Val.getBoolValue();
940 } while ((S = PM.getParent(S)));
946 static void diagnoseRepeatedUseOfWeak(Sema &S,
947 const sema::FunctionScopeInfo *CurFn,
949 const ParentMap &PM) {
950 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
951 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
952 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
954 ASTContext &Ctx = S.getASTContext();
956 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
958 // Extract all weak objects that are referenced more than once.
959 SmallVector<StmtUsesPair, 8> UsesByStmt;
960 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
962 const WeakUseVector &Uses = I->second;
964 // Find the first read of the weak object.
965 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
966 for ( ; UI != UE; ++UI) {
971 // If there were only writes to this object, don't warn.
975 // If there was only one read, followed by any number of writes, and the
976 // read is not within a loop, don't warn. Additionally, don't warn in a
977 // loop if the base object is a local variable -- local variables are often
979 if (UI == Uses.begin()) {
980 WeakUseVector::const_iterator UI2 = UI;
981 for (++UI2; UI2 != UE; ++UI2)
986 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
989 const WeakObjectProfileTy &Profile = I->first;
990 if (!Profile.isExactProfile())
993 const NamedDecl *Base = Profile.getBase();
995 Base = Profile.getProperty();
996 assert(Base && "A profile always has a base or property.");
998 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
999 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1004 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1007 if (UsesByStmt.empty())
1010 // Sort by first use so that we emit the warnings in a deterministic order.
1011 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1012 StmtUseSorter(S.getSourceManager()));
1014 // Classify the current code body for better warning text.
1015 // This enum should stay in sync with the cases in
1016 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1017 // FIXME: Should we use a common classification enum and the same set of
1018 // possibilities all throughout Sema?
1026 if (isa<sema::BlockScopeInfo>(CurFn))
1027 FunctionKind = Block;
1028 else if (isa<sema::LambdaScopeInfo>(CurFn))
1029 FunctionKind = Lambda;
1030 else if (isa<ObjCMethodDecl>(D))
1031 FunctionKind = Method;
1033 FunctionKind = Function;
1035 // Iterate through the sorted problems and emit warnings for each.
1036 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1037 E = UsesByStmt.end();
1039 const Stmt *FirstRead = I->first;
1040 const WeakObjectProfileTy &Key = I->second->first;
1041 const WeakUseVector &Uses = I->second->second;
1043 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1044 // may not contain enough information to determine that these are different
1045 // properties. We can only be 100% sure of a repeated use in certain cases,
1046 // and we adjust the diagnostic kind accordingly so that the less certain
1047 // case can be turned off if it is too noisy.
1049 if (Key.isExactProfile())
1050 DiagKind = diag::warn_arc_repeated_use_of_weak;
1052 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1054 // Classify the weak object being accessed for better warning text.
1055 // This enum should stay in sync with the cases in
1056 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1064 const NamedDecl *D = Key.getProperty();
1065 if (isa<VarDecl>(D))
1066 ObjectKind = Variable;
1067 else if (isa<ObjCPropertyDecl>(D))
1068 ObjectKind = Property;
1069 else if (isa<ObjCMethodDecl>(D))
1070 ObjectKind = ImplicitProperty;
1071 else if (isa<ObjCIvarDecl>(D))
1074 llvm_unreachable("Unexpected weak object kind!");
1076 // Show the first time the object was read.
1077 S.Diag(FirstRead->getLocStart(), DiagKind)
1078 << ObjectKind << D << FunctionKind
1079 << FirstRead->getSourceRange();
1081 // Print all the other accesses as notes.
1082 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1084 if (UI->getUseExpr() == FirstRead)
1086 S.Diag(UI->getUseExpr()->getLocStart(),
1087 diag::note_arc_weak_also_accessed_here)
1088 << UI->getUseExpr()->getSourceRange();
1096 bool operator()(const UninitUse &a, const UninitUse &b) {
1097 // Prefer a more confident report over a less confident one.
1098 if (a.getKind() != b.getKind())
1099 return a.getKind() > b.getKind();
1100 SourceLocation aLoc = a.getUser()->getLocStart();
1101 SourceLocation bLoc = b.getUser()->getLocStart();
1102 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1106 class UninitValsDiagReporter : public UninitVariablesHandler {
1108 typedef SmallVector<UninitUse, 2> UsesVec;
1109 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
1113 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1114 ~UninitValsDiagReporter() {
1118 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
1120 uses = new UsesMap();
1122 UsesMap::mapped_type &V = (*uses)[vd];
1123 UsesVec *&vec = V.first;
1125 vec = new UsesVec();
1130 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
1131 getUses(vd).first->push_back(use);
1134 void handleSelfInit(const VarDecl *vd) {
1135 getUses(vd).second = true;
1138 void flushDiagnostics() {
1142 // FIXME: This iteration order, and thus the resulting diagnostic order,
1143 // is nondeterministic.
1144 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1145 const VarDecl *vd = i->first;
1146 const UsesMap::mapped_type &V = i->second;
1148 UsesVec *vec = V.first;
1149 bool hasSelfInit = V.second;
1151 // Specially handle the case where we have uses of an uninitialized
1152 // variable, but the root cause is an idiomatic self-init. We want
1153 // to report the diagnostic at the self-init since that is the root cause.
1154 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1155 DiagnoseUninitializedUse(S, vd,
1156 UninitUse(vd->getInit()->IgnoreParenCasts(),
1157 /* isAlwaysUninit */ true),
1158 /* alwaysReportSelfInit */ true);
1160 // Sort the uses by their SourceLocations. While not strictly
1161 // guaranteed to produce them in line/column order, this will provide
1162 // a stable ordering.
1163 std::sort(vec->begin(), vec->end(), SLocSort());
1165 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1167 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1168 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1170 if (DiagnoseUninitializedUse(S, vd, Use))
1171 // Skip further diagnostics for this variable. We try to warn only
1172 // on the first point at which a variable is used uninitialized.
1177 // Release the uses vector.
1184 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1185 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
1186 if (i->getKind() == UninitUse::Always) {
1196 //===----------------------------------------------------------------------===//
1198 //===----------------------------------------------------------------------===//
1200 namespace thread_safety {
1201 typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1202 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1203 typedef std::list<DelayedDiag> DiagList;
1205 struct SortDiagBySourceLocation {
1207 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1209 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1210 // Although this call will be slow, this is only called when outputting
1211 // multiple warnings.
1212 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1217 class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1220 SourceLocation FunLocation, FunEndLocation;
1223 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
1224 // Gracefully handle rare cases when the analysis can't get a more
1225 // precise source location.
1228 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1229 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1233 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1234 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
1236 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1237 /// We need to output diagnostics produced while iterating through
1238 /// the lockset in deterministic order, so this function orders diagnostics
1239 /// and outputs them.
1240 void emitDiagnostics() {
1241 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1242 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1244 S.Diag(I->first.first, I->first.second);
1245 const OptionalNotes &Notes = I->second;
1246 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1247 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1251 void handleInvalidLockExp(SourceLocation Loc) {
1252 PartialDiagnosticAt Warning(Loc,
1253 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1254 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1256 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1257 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1260 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1261 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1264 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1265 SourceLocation LocEndOfScope,
1267 unsigned DiagID = 0;
1269 case LEK_LockedSomePredecessors:
1270 DiagID = diag::warn_lock_some_predecessors;
1272 case LEK_LockedSomeLoopIterations:
1273 DiagID = diag::warn_expecting_lock_held_on_loop;
1275 case LEK_LockedAtEndOfFunction:
1276 DiagID = diag::warn_no_unlock;
1278 case LEK_NotLockedAtEndOfFunction:
1279 DiagID = diag::warn_expecting_locked;
1282 if (LocEndOfScope.isInvalid())
1283 LocEndOfScope = FunEndLocation;
1285 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
1286 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1287 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1291 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1292 SourceLocation Loc2) {
1293 PartialDiagnosticAt Warning(
1294 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1295 PartialDiagnosticAt Note(
1296 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1297 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1300 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1301 AccessKind AK, SourceLocation Loc) {
1302 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1303 && "Only works for variables");
1304 unsigned DiagID = POK == POK_VarAccess?
1305 diag::warn_variable_requires_any_lock:
1306 diag::warn_var_deref_requires_any_lock;
1307 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1308 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1309 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1312 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
1313 Name LockName, LockKind LK, SourceLocation Loc,
1314 Name *PossibleMatch) {
1315 unsigned DiagID = 0;
1316 if (PossibleMatch) {
1319 DiagID = diag::warn_variable_requires_lock_precise;
1321 case POK_VarDereference:
1322 DiagID = diag::warn_var_deref_requires_lock_precise;
1324 case POK_FunctionCall:
1325 DiagID = diag::warn_fun_requires_lock_precise;
1328 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1329 << D->getNameAsString() << LockName << LK);
1330 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1332 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1336 DiagID = diag::warn_variable_requires_lock;
1338 case POK_VarDereference:
1339 DiagID = diag::warn_var_deref_requires_lock;
1341 case POK_FunctionCall:
1342 DiagID = diag::warn_fun_requires_lock;
1345 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1346 << D->getNameAsString() << LockName << LK);
1347 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1351 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
1352 PartialDiagnosticAt Warning(Loc,
1353 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1354 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1361 //===----------------------------------------------------------------------===//
1362 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1363 // warnings on a function, method, or block.
1364 //===----------------------------------------------------------------------===//
1366 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1367 enableCheckFallThrough = 1;
1368 enableCheckUnreachable = 0;
1369 enableThreadSafetyAnalysis = 0;
1372 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1374 NumFunctionsAnalyzed(0),
1375 NumFunctionsWithBadCFGs(0),
1377 MaxCFGBlocksPerFunction(0),
1378 NumUninitAnalysisFunctions(0),
1379 NumUninitAnalysisVariables(0),
1380 MaxUninitAnalysisVariablesPerFunction(0),
1381 NumUninitAnalysisBlockVisits(0),
1382 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1383 DiagnosticsEngine &D = S.getDiagnostics();
1384 DefaultPolicy.enableCheckUnreachable = (unsigned)
1385 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
1386 DiagnosticsEngine::Ignored);
1387 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1388 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
1389 DiagnosticsEngine::Ignored);
1393 static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
1394 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1395 i = fscope->PossiblyUnreachableDiags.begin(),
1396 e = fscope->PossiblyUnreachableDiags.end();
1398 const sema::PossiblyUnreachableDiag &D = *i;
1399 S.Diag(D.Loc, D.PD);
1404 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1405 sema::FunctionScopeInfo *fscope,
1406 const Decl *D, const BlockExpr *blkExpr) {
1408 // We avoid doing analysis-based warnings when there are errors for
1410 // (1) The CFGs often can't be constructed (if the body is invalid), so
1411 // don't bother trying.
1412 // (2) The code already has problems; running the analysis just takes more
1414 DiagnosticsEngine &Diags = S.getDiagnostics();
1416 // Do not do any analysis for declarations in system headers if we are
1417 // going to just ignore them.
1418 if (Diags.getSuppressSystemWarnings() &&
1419 S.SourceMgr.isInSystemHeader(D->getLocation()))
1422 // For code in dependent contexts, we'll do this at instantiation time.
1423 if (cast<DeclContext>(D)->isDependentContext())
1426 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1427 // Flush out any possibly unreachable diagnostics.
1428 flushDiagnostics(S, fscope);
1432 const Stmt *Body = D->getBody();
1435 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
1437 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1438 // explosion for destrutors that can result and the compile time hit.
1439 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1440 AC.getCFGBuildOptions().AddEHEdges = false;
1441 AC.getCFGBuildOptions().AddInitializers = true;
1442 AC.getCFGBuildOptions().AddImplicitDtors = true;
1443 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1445 // Force that certain expressions appear as CFGElements in the CFG. This
1446 // is used to speed up various analyses.
1447 // FIXME: This isn't the right factoring. This is here for initial
1448 // prototyping, but we need a way for analyses to say what expressions they
1449 // expect to always be CFGElements and then fill in the BuildOptions
1450 // appropriately. This is essentially a layering violation.
1451 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
1452 // Unreachable code analysis and thread safety require a linearized CFG.
1453 AC.getCFGBuildOptions().setAllAlwaysAdd();
1456 AC.getCFGBuildOptions()
1457 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1458 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1459 .setAlwaysAdd(Stmt::BlockExprClass)
1460 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1461 .setAlwaysAdd(Stmt::DeclRefExprClass)
1462 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1463 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1464 .setAlwaysAdd(Stmt::AttributedStmtClass);
1467 // Construct the analysis context with the specified CFG build options.
1469 // Emit delayed diagnostics.
1470 if (!fscope->PossiblyUnreachableDiags.empty()) {
1471 bool analyzed = false;
1473 // Register the expressions with the CFGBuilder.
1474 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1475 i = fscope->PossiblyUnreachableDiags.begin(),
1476 e = fscope->PossiblyUnreachableDiags.end();
1478 if (const Stmt *stmt = i->stmt)
1479 AC.registerForcedBlockExpression(stmt);
1484 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1485 i = fscope->PossiblyUnreachableDiags.begin(),
1486 e = fscope->PossiblyUnreachableDiags.end();
1489 const sema::PossiblyUnreachableDiag &D = *i;
1490 bool processed = false;
1491 if (const Stmt *stmt = i->stmt) {
1492 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
1493 CFGReverseBlockReachabilityAnalysis *cra =
1494 AC.getCFGReachablityAnalysis();
1495 // FIXME: We should be able to assert that block is non-null, but
1496 // the CFG analysis can skip potentially-evaluated expressions in
1497 // edge cases; see test/Sema/vla-2.c.
1499 // Can this block be reached from the entrance?
1500 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
1501 S.Diag(D.Loc, D.PD);
1506 // Emit the warning anyway if we cannot map to a basic block.
1507 S.Diag(D.Loc, D.PD);
1513 flushDiagnostics(S, fscope);
1517 // Warning: check missing 'return'
1518 if (P.enableCheckFallThrough) {
1519 const CheckFallThroughDiagnostics &CD =
1520 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
1521 : (isa<CXXMethodDecl>(D) &&
1522 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1523 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1524 ? CheckFallThroughDiagnostics::MakeForLambda()
1525 : CheckFallThroughDiagnostics::MakeForFunction(D));
1526 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
1529 // Warning: check for unreachable code
1530 if (P.enableCheckUnreachable) {
1531 // Only check for unreachable code on non-template instantiations.
1532 // Different template instantiations can effectively change the control-flow
1533 // and it is very difficult to prove that a snippet of code in a template
1534 // is unreachable for all instantiations.
1535 bool isTemplateInstantiation = false;
1536 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1537 isTemplateInstantiation = Function->isTemplateInstantiation();
1538 if (!isTemplateInstantiation)
1539 CheckUnreachable(S, AC);
1542 // Check for thread safety violations
1543 if (P.enableThreadSafetyAnalysis) {
1544 SourceLocation FL = AC.getDecl()->getLocation();
1545 SourceLocation FEL = AC.getDecl()->getLocEnd();
1546 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
1547 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1548 Reporter.emitDiagnostics();
1551 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
1552 != DiagnosticsEngine::Ignored ||
1553 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1554 != DiagnosticsEngine::Ignored ||
1555 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
1556 != DiagnosticsEngine::Ignored) {
1557 if (CFG *cfg = AC.getCFG()) {
1558 UninitValsDiagReporter reporter(S);
1559 UninitVariablesAnalysisStats stats;
1560 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
1561 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
1564 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1565 ++NumUninitAnalysisFunctions;
1566 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1567 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1568 MaxUninitAnalysisVariablesPerFunction =
1569 std::max(MaxUninitAnalysisVariablesPerFunction,
1570 stats.NumVariablesAnalyzed);
1571 MaxUninitAnalysisBlockVisitsPerFunction =
1572 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1573 stats.NumBlockVisits);
1578 bool FallThroughDiagFull =
1579 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1580 D->getLocStart()) != DiagnosticsEngine::Ignored;
1581 bool FallThroughDiagPerFunction =
1582 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
1583 D->getLocStart()) != DiagnosticsEngine::Ignored;
1584 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
1585 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
1588 if (S.getLangOpts().ObjCARCWeak &&
1589 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1590 D->getLocStart()) != DiagnosticsEngine::Ignored)
1591 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
1593 // Collect statistics about the CFG if it was built.
1594 if (S.CollectStats && AC.isCFGBuilt()) {
1595 ++NumFunctionsAnalyzed;
1596 if (CFG *cfg = AC.getCFG()) {
1597 // If we successfully built a CFG for this context, record some more
1598 // detail information about it.
1599 NumCFGBlocks += cfg->getNumBlockIDs();
1600 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
1601 cfg->getNumBlockIDs());
1603 ++NumFunctionsWithBadCFGs;
1608 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1609 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1611 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1612 unsigned AvgCFGBlocksPerFunction =
1613 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1614 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1615 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1616 << " " << NumCFGBlocks << " CFG blocks built.\n"
1617 << " " << AvgCFGBlocksPerFunction
1618 << " average CFG blocks per function.\n"
1619 << " " << MaxCFGBlocksPerFunction
1620 << " max CFG blocks per function.\n";
1622 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1623 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1624 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1625 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1626 llvm::errs() << NumUninitAnalysisFunctions
1627 << " functions analyzed for uninitialiazed variables\n"
1628 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1629 << " " << AvgUninitVariablesPerFunction
1630 << " average variables per function.\n"
1631 << " " << MaxUninitAnalysisVariablesPerFunction
1632 << " max variables per function.\n"
1633 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1634 << " " << AvgUninitBlockVisitsPerFunction
1635 << " average block visits per function.\n"
1636 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1637 << " max block visits per function.\n";