1 //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines analysis_warnings::[Policy,Executor].
11 // Together they are used by Sema to issue warnings based on inexpensive
12 // static analysis algorithms in libAnalysis.
14 //===----------------------------------------------------------------------===//
16 #include "clang/Sema/AnalysisBasedWarnings.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
28 #include "clang/Analysis/Analyses/Consumed.h"
29 #include "clang/Analysis/Analyses/ReachableCode.h"
30 #include "clang/Analysis/Analyses/ThreadSafety.h"
31 #include "clang/Analysis/Analyses/UninitializedValues.h"
32 #include "clang/Analysis/AnalysisContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/CFGStmtMap.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Lex/Lexer.h"
38 #include "clang/Lex/Preprocessor.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/FoldingSet.h"
44 #include "llvm/ADT/ImmutableMap.h"
45 #include "llvm/ADT/MapVector.h"
46 #include "llvm/ADT/PostOrderIterator.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/StringRef.h"
50 #include "llvm/Support/Casting.h"
56 using namespace clang;
58 //===----------------------------------------------------------------------===//
59 // Unreachable code analysis.
60 //===----------------------------------------------------------------------===//
63 class UnreachableCodeHandler : public reachable_code::Callback {
66 UnreachableCodeHandler(Sema &s) : S(s) {}
68 void HandleUnreachable(reachable_code::UnreachableKind UK,
70 SourceRange SilenceableCondVal,
72 SourceRange R2) override {
73 unsigned diag = diag::warn_unreachable;
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
78 case reachable_code::UK_Return:
79 diag = diag::warn_unreachable_return;
81 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
84 case reachable_code::UK_Other:
88 S.Diag(L, diag) << R1 << R2;
90 SourceLocation Open = SilenceableCondVal.getBegin();
92 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
94 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
104 /// CheckUnreachable - Check for unreachable code.
105 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
106 // As a heuristic prune all diagnostics not in the main file. Currently
107 // the majority of warnings in headers are false positives. These
108 // are largely caused by configuration state, e.g. preprocessor
109 // defined code, etc.
111 // Note that this is also a performance optimization. Analyzing
112 // headers many times can be expensive.
113 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
116 UnreachableCodeHandler UC(S);
117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
120 /// \brief Warn on logical operator errors in CFGBuilder
121 class LogicalErrorHandler : public CFGCallback {
125 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
127 static bool HasMacroID(const Expr *E) {
128 if (E->getExprLoc().isMacroID())
131 // Recurse to children.
132 for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
134 if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
135 if (HasMacroID(SubExpr))
141 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {
145 SourceRange DiagRange = B->getSourceRange();
146 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
147 << DiagRange << isAlwaysTrue;
150 void compareBitwiseEquality(const BinaryOperator *B, bool isAlwaysTrue) {
154 SourceRange DiagRange = B->getSourceRange();
155 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
156 << DiagRange << isAlwaysTrue;
161 //===----------------------------------------------------------------------===//
162 // Check for infinite self-recursion in functions
163 //===----------------------------------------------------------------------===//
165 // All blocks are in one of three states. States are ordered so that blocks
166 // can only move to higher states.
167 enum RecursiveState {
170 FoundPathWithNoRecursiveCall
173 static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
174 CFGBlock &Block, unsigned ExitID,
175 llvm::SmallVectorImpl<RecursiveState> &States,
176 RecursiveState State) {
177 unsigned ID = Block.getBlockID();
179 // A block's state can only move to a higher state.
180 if (States[ID] >= State)
185 // Found a path to the exit node without a recursive call.
186 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
189 if (State == FoundPathWithNoRecursiveCall) {
190 // If the current state is FoundPathWithNoRecursiveCall, the successors
191 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
192 // which, process all the Stmt's in this block to find any recursive calls.
193 for (const auto &B : Block) {
194 if (B.getKind() != CFGElement::Statement)
197 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
198 if (CE && CE->getCalleeDecl() &&
199 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
201 // Skip function calls which are qualified with a templated class.
202 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
203 CE->getCallee()->IgnoreParenImpCasts())) {
204 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
205 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
206 isa<TemplateSpecializationType>(NNS->getAsType())) {
212 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
213 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
214 !MCE->getMethodDecl()->isVirtual()) {
226 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
229 checkForFunctionCall(S, FD, **I, ExitID, States, State);
232 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
234 AnalysisDeclContext &AC) {
235 FD = FD->getCanonicalDecl();
237 // Only run on non-templated functions and non-templated members of
238 // templated classes.
239 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
240 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
243 CFG *cfg = AC.getCFG();
246 // If the exit block is unreachable, skip processing the function.
247 if (cfg->getExit().pred_empty())
250 // Mark all nodes as FoundNoPath, then begin processing the entry block.
251 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
253 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
254 states, FoundPathWithNoRecursiveCall);
256 // Check that the exit block is reachable. This prevents triggering the
257 // warning on functions that do not terminate.
258 if (states[cfg->getExit().getBlockID()] == FoundPath)
259 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
262 //===----------------------------------------------------------------------===//
263 // Check for missing return value.
264 //===----------------------------------------------------------------------===//
266 enum ControlFlowKind {
271 NeverFallThroughOrReturn
274 /// CheckFallThrough - Check that we don't fall off the end of a
275 /// Statement that should return a value.
277 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
278 /// MaybeFallThrough iff we might or might not fall off the end,
279 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
280 /// return. We assume NeverFallThrough iff we never fall off the end of the
281 /// statement but we may return. We assume that functions not marked noreturn
283 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
284 CFG *cfg = AC.getCFG();
285 if (!cfg) return UnknownFallThrough;
287 // The CFG leaves in dead things, and we don't want the dead code paths to
288 // confuse us, so we mark all live things first.
289 llvm::BitVector live(cfg->getNumBlockIDs());
290 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
293 bool AddEHEdges = AC.getAddEHEdges();
294 if (!AddEHEdges && count != cfg->getNumBlockIDs())
295 // When there are things remaining dead, and we didn't add EH edges
296 // from CallExprs to the catch clauses, we have to go back and
297 // mark them as live.
298 for (const auto *B : *cfg) {
299 if (!live[B->getBlockID()]) {
300 if (B->pred_begin() == B->pred_end()) {
301 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
302 // When not adding EH edges from calls, catch clauses
303 // can otherwise seem dead. Avoid noting them as dead.
304 count += reachable_code::ScanReachableFromBlock(B, live);
310 // Now we know what is live, we check the live precessors of the exit block
311 // and look for fall through paths, being careful to ignore normal returns,
312 // and exceptional paths.
313 bool HasLiveReturn = false;
314 bool HasFakeEdge = false;
315 bool HasPlainEdge = false;
316 bool HasAbnormalEdge = false;
318 // Ignore default cases that aren't likely to be reachable because all
319 // enums in a switch(X) have explicit case statements.
320 CFGBlock::FilterOptions FO;
321 FO.IgnoreDefaultsWithCoveredEnums = 1;
323 for (CFGBlock::filtered_pred_iterator
324 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
325 const CFGBlock& B = **I;
326 if (!live[B.getBlockID()])
329 // Skip blocks which contain an element marked as no-return. They don't
330 // represent actually viable edges into the exit block, so mark them as
332 if (B.hasNoReturnElement()) {
333 HasAbnormalEdge = true;
337 // Destructors can appear after the 'return' in the CFG. This is
338 // normal. We need to look pass the destructors for the return
339 // statement (if it exists).
340 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
342 for ( ; ri != re ; ++ri)
343 if (ri->getAs<CFGStmt>())
346 // No more CFGElements in the block?
348 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
349 HasAbnormalEdge = true;
352 // A labeled empty statement, or the entry block...
357 CFGStmt CS = ri->castAs<CFGStmt>();
358 const Stmt *S = CS.getStmt();
359 if (isa<ReturnStmt>(S)) {
360 HasLiveReturn = true;
363 if (isa<ObjCAtThrowStmt>(S)) {
367 if (isa<CXXThrowExpr>(S)) {
371 if (isa<MSAsmStmt>(S)) {
372 // TODO: Verify this is correct.
374 HasLiveReturn = true;
377 if (isa<CXXTryStmt>(S)) {
378 HasAbnormalEdge = true;
381 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
383 HasAbnormalEdge = true;
391 return NeverFallThrough;
392 return NeverFallThroughOrReturn;
394 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
395 return MaybeFallThrough;
396 // This says AlwaysFallThrough for calls to functions that are not marked
397 // noreturn, that don't return. If people would like this warning to be more
398 // accurate, such functions should be marked as noreturn.
399 return AlwaysFallThrough;
404 struct CheckFallThroughDiagnostics {
405 unsigned diag_MaybeFallThrough_HasNoReturn;
406 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
407 unsigned diag_AlwaysFallThrough_HasNoReturn;
408 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
409 unsigned diag_NeverFallThroughOrReturn;
410 enum { Function, Block, Lambda } funMode;
411 SourceLocation FuncLoc;
413 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
414 CheckFallThroughDiagnostics D;
415 D.FuncLoc = Func->getLocation();
416 D.diag_MaybeFallThrough_HasNoReturn =
417 diag::warn_falloff_noreturn_function;
418 D.diag_MaybeFallThrough_ReturnsNonVoid =
419 diag::warn_maybe_falloff_nonvoid_function;
420 D.diag_AlwaysFallThrough_HasNoReturn =
421 diag::warn_falloff_noreturn_function;
422 D.diag_AlwaysFallThrough_ReturnsNonVoid =
423 diag::warn_falloff_nonvoid_function;
425 // Don't suggest that virtual functions be marked "noreturn", since they
426 // might be overridden by non-noreturn functions.
427 bool isVirtualMethod = false;
428 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
429 isVirtualMethod = Method->isVirtual();
431 // Don't suggest that template instantiations be marked "noreturn"
432 bool isTemplateInstantiation = false;
433 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
434 isTemplateInstantiation = Function->isTemplateInstantiation();
436 if (!isVirtualMethod && !isTemplateInstantiation)
437 D.diag_NeverFallThroughOrReturn =
438 diag::warn_suggest_noreturn_function;
440 D.diag_NeverFallThroughOrReturn = 0;
442 D.funMode = Function;
446 static CheckFallThroughDiagnostics MakeForBlock() {
447 CheckFallThroughDiagnostics D;
448 D.diag_MaybeFallThrough_HasNoReturn =
449 diag::err_noreturn_block_has_return_expr;
450 D.diag_MaybeFallThrough_ReturnsNonVoid =
451 diag::err_maybe_falloff_nonvoid_block;
452 D.diag_AlwaysFallThrough_HasNoReturn =
453 diag::err_noreturn_block_has_return_expr;
454 D.diag_AlwaysFallThrough_ReturnsNonVoid =
455 diag::err_falloff_nonvoid_block;
456 D.diag_NeverFallThroughOrReturn = 0;
461 static CheckFallThroughDiagnostics MakeForLambda() {
462 CheckFallThroughDiagnostics D;
463 D.diag_MaybeFallThrough_HasNoReturn =
464 diag::err_noreturn_lambda_has_return_expr;
465 D.diag_MaybeFallThrough_ReturnsNonVoid =
466 diag::warn_maybe_falloff_nonvoid_lambda;
467 D.diag_AlwaysFallThrough_HasNoReturn =
468 diag::err_noreturn_lambda_has_return_expr;
469 D.diag_AlwaysFallThrough_ReturnsNonVoid =
470 diag::warn_falloff_nonvoid_lambda;
471 D.diag_NeverFallThroughOrReturn = 0;
476 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
477 bool HasNoReturn) const {
478 if (funMode == Function) {
479 return (ReturnsVoid ||
480 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
483 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
486 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
489 // For blocks / lambdas.
490 return ReturnsVoid && !HasNoReturn;
496 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
497 /// function that should return a value. Check that we don't fall off the end
498 /// of a noreturn function. We assume that functions and blocks not marked
499 /// noreturn will return.
500 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
501 const BlockExpr *blkExpr,
502 const CheckFallThroughDiagnostics& CD,
503 AnalysisDeclContext &AC) {
505 bool ReturnsVoid = false;
506 bool HasNoReturn = false;
508 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
509 ReturnsVoid = FD->getReturnType()->isVoidType();
510 HasNoReturn = FD->isNoReturn();
512 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
513 ReturnsVoid = MD->getReturnType()->isVoidType();
514 HasNoReturn = MD->hasAttr<NoReturnAttr>();
516 else if (isa<BlockDecl>(D)) {
517 QualType BlockTy = blkExpr->getType();
518 if (const FunctionType *FT =
519 BlockTy->getPointeeType()->getAs<FunctionType>()) {
520 if (FT->getReturnType()->isVoidType())
522 if (FT->getNoReturnAttr())
527 DiagnosticsEngine &Diags = S.getDiagnostics();
529 // Short circuit for compilation speed.
530 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
533 // FIXME: Function try block
534 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
535 switch (CheckFallThrough(AC)) {
536 case UnknownFallThrough:
539 case MaybeFallThrough:
541 S.Diag(Compound->getRBracLoc(),
542 CD.diag_MaybeFallThrough_HasNoReturn);
543 else if (!ReturnsVoid)
544 S.Diag(Compound->getRBracLoc(),
545 CD.diag_MaybeFallThrough_ReturnsNonVoid);
547 case AlwaysFallThrough:
549 S.Diag(Compound->getRBracLoc(),
550 CD.diag_AlwaysFallThrough_HasNoReturn);
551 else if (!ReturnsVoid)
552 S.Diag(Compound->getRBracLoc(),
553 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
555 case NeverFallThroughOrReturn:
556 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
557 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
558 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
560 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
561 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
564 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
568 case NeverFallThrough:
574 //===----------------------------------------------------------------------===//
576 //===----------------------------------------------------------------------===//
579 /// ContainsReference - A visitor class to search for references to
580 /// a particular declaration (the needle) within any evaluated component of an
581 /// expression (recursively).
582 class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
584 const DeclRefExpr *Needle;
587 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
588 : EvaluatedExprVisitor<ContainsReference>(Context),
589 FoundReference(false), Needle(Needle) {}
591 void VisitExpr(Expr *E) {
592 // Stop evaluating if we already have a reference.
596 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
599 void VisitDeclRefExpr(DeclRefExpr *E) {
601 FoundReference = true;
603 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
606 bool doesContainReference() const { return FoundReference; }
610 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
611 QualType VariableTy = VD->getType().getCanonicalType();
612 if (VariableTy->isBlockPointerType() &&
613 !VD->hasAttr<BlocksAttr>()) {
614 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
616 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
620 // Don't issue a fixit if there is already an initializer.
624 // Don't suggest a fixit inside macros.
625 if (VD->getLocEnd().isMacroID())
628 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
630 // Suggest possible initialization (if any).
631 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
635 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
636 << FixItHint::CreateInsertion(Loc, Init);
640 /// Create a fixit to remove an if-like statement, on the assumption that its
641 /// condition is CondVal.
642 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
643 const Stmt *Else, bool CondVal,
644 FixItHint &Fixit1, FixItHint &Fixit2) {
646 // If condition is always true, remove all but the 'then'.
647 Fixit1 = FixItHint::CreateRemoval(
648 CharSourceRange::getCharRange(If->getLocStart(),
649 Then->getLocStart()));
651 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
652 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
653 Fixit2 = FixItHint::CreateRemoval(
654 SourceRange(ElseKwLoc, Else->getLocEnd()));
657 // If condition is always false, remove all but the 'else'.
659 Fixit1 = FixItHint::CreateRemoval(
660 CharSourceRange::getCharRange(If->getLocStart(),
661 Else->getLocStart()));
663 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
667 /// DiagUninitUse -- Helper function to produce a diagnostic for an
668 /// uninitialized use of a variable.
669 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
670 bool IsCapturedByBlock) {
671 bool Diagnosed = false;
673 switch (Use.getKind()) {
674 case UninitUse::Always:
675 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
676 << VD->getDeclName() << IsCapturedByBlock
677 << Use.getUser()->getSourceRange();
680 case UninitUse::AfterDecl:
681 case UninitUse::AfterCall:
682 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
683 << VD->getDeclName() << IsCapturedByBlock
684 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
685 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
686 << VD->getSourceRange();
687 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
688 << IsCapturedByBlock << Use.getUser()->getSourceRange();
691 case UninitUse::Maybe:
692 case UninitUse::Sometimes:
693 // Carry on to report sometimes-uninitialized branches, if possible,
694 // or a 'may be used uninitialized' diagnostic otherwise.
698 // Diagnose each branch which leads to a sometimes-uninitialized use.
699 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
701 assert(Use.getKind() == UninitUse::Sometimes);
703 const Expr *User = Use.getUser();
704 const Stmt *Term = I->Terminator;
706 // Information used when building the diagnostic.
711 // FixIts to suppress the diagnostic by removing the dead condition.
712 // For all binary terminators, branch 0 is taken if the condition is true,
713 // and branch 1 is taken if the condition is false.
714 int RemoveDiagKind = -1;
715 const char *FixitStr =
716 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
717 : (I->Output ? "1" : "0");
718 FixItHint Fixit1, Fixit2;
720 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
722 // Don't know how to report this. Just fall back to 'may be used
723 // uninitialized'. FIXME: Can this happen?
726 // "condition is true / condition is false".
727 case Stmt::IfStmtClass: {
728 const IfStmt *IS = cast<IfStmt>(Term);
731 Range = IS->getCond()->getSourceRange();
733 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
734 I->Output, Fixit1, Fixit2);
737 case Stmt::ConditionalOperatorClass: {
738 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
741 Range = CO->getCond()->getSourceRange();
743 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
744 I->Output, Fixit1, Fixit2);
747 case Stmt::BinaryOperatorClass: {
748 const BinaryOperator *BO = cast<BinaryOperator>(Term);
749 if (!BO->isLogicalOp())
752 Str = BO->getOpcodeStr();
753 Range = BO->getLHS()->getSourceRange();
755 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
756 (BO->getOpcode() == BO_LOr && !I->Output))
757 // true && y -> y, false || y -> y.
758 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
759 BO->getOperatorLoc()));
761 // false && y -> false, true || y -> true.
762 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
766 // "loop is entered / loop is exited".
767 case Stmt::WhileStmtClass:
770 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
772 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
774 case Stmt::ForStmtClass:
777 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
780 Fixit1 = FixItHint::CreateRemoval(Range);
782 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
784 case Stmt::CXXForRangeStmtClass:
785 if (I->Output == 1) {
786 // The use occurs if a range-based for loop's body never executes.
787 // That may be impossible, and there's no syntactic fix for this,
788 // so treat it as a 'may be uninitialized' case.
793 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
796 // "condition is true / loop is exited".
797 case Stmt::DoStmtClass:
800 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
802 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
805 // "switch case is taken".
806 case Stmt::CaseStmtClass:
809 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
811 case Stmt::DefaultStmtClass:
814 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
818 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
819 << VD->getDeclName() << IsCapturedByBlock << DiagKind
820 << Str << I->Output << Range;
821 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
822 << IsCapturedByBlock << User->getSourceRange();
823 if (RemoveDiagKind != -1)
824 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
825 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
831 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
832 << VD->getDeclName() << IsCapturedByBlock
833 << Use.getUser()->getSourceRange();
836 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
837 /// uninitialized variable. This manages the different forms of diagnostic
838 /// emitted for particular types of uses. Returns true if the use was diagnosed
839 /// as a warning. If a particular use is one we omit warnings for, returns
841 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
842 const UninitUse &Use,
843 bool alwaysReportSelfInit = false) {
845 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
846 // Inspect the initializer of the variable declaration which is
847 // being referenced prior to its initialization. We emit
848 // specialized diagnostics for self-initialization, and we
849 // specifically avoid warning about self references which take the
854 // This is used to indicate to GCC that 'x' is intentionally left
855 // uninitialized. Proven code paths which access 'x' in
856 // an uninitialized state after this will still warn.
857 if (const Expr *Initializer = VD->getInit()) {
858 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
861 ContainsReference CR(S.Context, DRE);
862 CR.Visit(const_cast<Expr*>(Initializer));
863 if (CR.doesContainReference()) {
864 S.Diag(DRE->getLocStart(),
865 diag::warn_uninit_self_reference_in_init)
866 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
871 DiagUninitUse(S, VD, Use, false);
873 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
874 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
875 S.Diag(BE->getLocStart(),
876 diag::warn_uninit_byref_blockvar_captured_by_block)
877 << VD->getDeclName();
879 DiagUninitUse(S, VD, Use, true);
882 // Report where the variable was declared when the use wasn't within
883 // the initializer of that declaration & we didn't already suggest
884 // an initialization fixit.
885 if (!SuggestInitializationFixit(S, VD))
886 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
887 << VD->getDeclName();
893 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
895 FallthroughMapper(Sema &S)
896 : FoundSwitchStatements(false),
900 bool foundSwitchStatements() const { return FoundSwitchStatements; }
902 void markFallthroughVisited(const AttributedStmt *Stmt) {
903 bool Found = FallthroughStmts.erase(Stmt);
908 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
910 const AttrStmts &getFallthroughStmts() const {
911 return FallthroughStmts;
914 void fillReachableBlocks(CFG *Cfg) {
915 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
916 std::deque<const CFGBlock *> BlockQueue;
918 ReachableBlocks.insert(&Cfg->getEntry());
919 BlockQueue.push_back(&Cfg->getEntry());
920 // Mark all case blocks reachable to avoid problems with switching on
921 // constants, covered enums, etc.
922 // These blocks can contain fall-through annotations, and we don't want to
923 // issue a warn_fallthrough_attr_unreachable for them.
924 for (const auto *B : *Cfg) {
925 const Stmt *L = B->getLabel();
926 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
927 BlockQueue.push_back(B);
930 while (!BlockQueue.empty()) {
931 const CFGBlock *P = BlockQueue.front();
932 BlockQueue.pop_front();
933 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
936 if (*I && ReachableBlocks.insert(*I))
937 BlockQueue.push_back(*I);
942 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
943 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
945 int UnannotatedCnt = 0;
948 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
949 while (!BlockQueue.empty()) {
950 const CFGBlock *P = BlockQueue.front();
951 BlockQueue.pop_front();
954 const Stmt *Term = P->getTerminator();
955 if (Term && isa<SwitchStmt>(Term))
956 continue; // Switch statement, good.
958 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
959 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
960 continue; // Previous case label has no statements, good.
962 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
963 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
964 continue; // Case label is preceded with a normal label, good.
966 if (!ReachableBlocks.count(P)) {
967 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
969 ElemIt != ElemEnd; ++ElemIt) {
970 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
971 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
972 S.Diag(AS->getLocStart(),
973 diag::warn_fallthrough_attr_unreachable);
974 markFallthroughVisited(AS);
978 // Don't care about other unreachable statements.
981 // If there are no unreachable statements, this may be a special
984 // A a; // A has a destructor.
987 // // <<<< This place is represented by a 'hanging' CFG block.
992 const Stmt *LastStmt = getLastStmt(*P);
993 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
994 markFallthroughVisited(AS);
996 continue; // Fallthrough annotation, good.
999 if (!LastStmt) { // This block contains no executable statements.
1000 // Traverse its predecessors.
1001 std::copy(P->pred_begin(), P->pred_end(),
1002 std::back_inserter(BlockQueue));
1008 return !!UnannotatedCnt;
1011 // RecursiveASTVisitor setup.
1012 bool shouldWalkTypesOfTypeLocs() const { return false; }
1014 bool VisitAttributedStmt(AttributedStmt *S) {
1015 if (asFallThroughAttr(S))
1016 FallthroughStmts.insert(S);
1020 bool VisitSwitchStmt(SwitchStmt *S) {
1021 FoundSwitchStatements = true;
1025 // We don't want to traverse local type declarations. We analyze their
1026 // methods separately.
1027 bool TraverseDecl(Decl *D) { return true; }
1029 // We analyze lambda bodies separately. Skip them here.
1030 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1034 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1035 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1036 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1042 static const Stmt *getLastStmt(const CFGBlock &B) {
1043 if (const Stmt *Term = B.getTerminator())
1045 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1047 ElemIt != ElemEnd; ++ElemIt) {
1048 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1049 return CS->getStmt();
1051 // Workaround to detect a statement thrown out by CFGBuilder:
1052 // case X: {} case Y:
1053 // case X: ; case Y:
1054 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1055 if (!isa<SwitchCase>(SW->getSubStmt()))
1056 return SW->getSubStmt();
1061 bool FoundSwitchStatements;
1062 AttrStmts FallthroughStmts;
1064 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1068 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1070 // Only perform this analysis when using C++11. There is no good workflow
1071 // for this warning when not using C++11. There is no good way to silence
1072 // the warning (no attribute is available) unless we are using C++11's support
1073 // for generalized attributes. Once could use pragmas to silence the warning,
1074 // but as a general solution that is gross and not in the spirit of this
1077 // NOTE: This an intermediate solution. There are on-going discussions on
1078 // how to properly support this warning outside of C++11 with an annotation.
1079 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
1082 FallthroughMapper FM(S);
1083 FM.TraverseStmt(AC.getBody());
1085 if (!FM.foundSwitchStatements())
1088 if (PerFunction && FM.getFallthroughStmts().empty())
1091 CFG *Cfg = AC.getCFG();
1096 FM.fillReachableBlocks(Cfg);
1098 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
1099 const CFGBlock *B = *I;
1100 const Stmt *Label = B->getLabel();
1102 if (!Label || !isa<SwitchCase>(Label))
1107 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
1110 S.Diag(Label->getLocStart(),
1111 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1112 : diag::warn_unannotated_fallthrough);
1114 if (!AnnotatedCnt) {
1115 SourceLocation L = Label->getLocStart();
1118 if (S.getLangOpts().CPlusPlus11) {
1119 const Stmt *Term = B->getTerminator();
1120 // Skip empty cases.
1121 while (B->empty() && !Term && B->succ_size() == 1) {
1122 B = *B->succ_begin();
1123 Term = B->getTerminator();
1125 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1126 Preprocessor &PP = S.getPreprocessor();
1127 TokenValue Tokens[] = {
1128 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1129 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1130 tok::r_square, tok::r_square
1132 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1133 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1134 if (!MacroName.empty())
1135 AnnotationSpelling = MacroName;
1136 SmallString<64> TextToInsert(AnnotationSpelling);
1137 TextToInsert += "; ";
1138 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1139 AnnotationSpelling <<
1140 FixItHint::CreateInsertion(L, TextToInsert);
1143 S.Diag(L, diag::note_insert_break_fixit) <<
1144 FixItHint::CreateInsertion(L, "break; ");
1148 for (const auto *F : FM.getFallthroughStmts())
1149 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1152 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1157 switch (S->getStmtClass()) {
1158 case Stmt::ForStmtClass:
1159 case Stmt::WhileStmtClass:
1160 case Stmt::CXXForRangeStmtClass:
1161 case Stmt::ObjCForCollectionStmtClass:
1163 case Stmt::DoStmtClass: {
1164 const Expr *Cond = cast<DoStmt>(S)->getCond();
1166 if (!Cond->EvaluateAsInt(Val, Ctx))
1168 return Val.getBoolValue();
1173 } while ((S = PM.getParent(S)));
1179 static void diagnoseRepeatedUseOfWeak(Sema &S,
1180 const sema::FunctionScopeInfo *CurFn,
1182 const ParentMap &PM) {
1183 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1184 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1185 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1186 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1189 ASTContext &Ctx = S.getASTContext();
1191 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1193 // Extract all weak objects that are referenced more than once.
1194 SmallVector<StmtUsesPair, 8> UsesByStmt;
1195 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1197 const WeakUseVector &Uses = I->second;
1199 // Find the first read of the weak object.
1200 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1201 for ( ; UI != UE; ++UI) {
1206 // If there were only writes to this object, don't warn.
1210 // If there was only one read, followed by any number of writes, and the
1211 // read is not within a loop, don't warn. Additionally, don't warn in a
1212 // loop if the base object is a local variable -- local variables are often
1213 // changed in loops.
1214 if (UI == Uses.begin()) {
1215 WeakUseVector::const_iterator UI2 = UI;
1216 for (++UI2; UI2 != UE; ++UI2)
1217 if (UI2->isUnsafe())
1221 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1224 const WeakObjectProfileTy &Profile = I->first;
1225 if (!Profile.isExactProfile())
1228 const NamedDecl *Base = Profile.getBase();
1230 Base = Profile.getProperty();
1231 assert(Base && "A profile always has a base or property.");
1233 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1234 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1239 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1242 if (UsesByStmt.empty())
1245 // Sort by first use so that we emit the warnings in a deterministic order.
1246 SourceManager &SM = S.getSourceManager();
1247 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1248 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1249 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1250 RHS.first->getLocStart());
1253 // Classify the current code body for better warning text.
1254 // This enum should stay in sync with the cases in
1255 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1256 // FIXME: Should we use a common classification enum and the same set of
1257 // possibilities all throughout Sema?
1265 if (isa<sema::BlockScopeInfo>(CurFn))
1266 FunctionKind = Block;
1267 else if (isa<sema::LambdaScopeInfo>(CurFn))
1268 FunctionKind = Lambda;
1269 else if (isa<ObjCMethodDecl>(D))
1270 FunctionKind = Method;
1272 FunctionKind = Function;
1274 // Iterate through the sorted problems and emit warnings for each.
1275 for (const auto &P : UsesByStmt) {
1276 const Stmt *FirstRead = P.first;
1277 const WeakObjectProfileTy &Key = P.second->first;
1278 const WeakUseVector &Uses = P.second->second;
1280 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1281 // may not contain enough information to determine that these are different
1282 // properties. We can only be 100% sure of a repeated use in certain cases,
1283 // and we adjust the diagnostic kind accordingly so that the less certain
1284 // case can be turned off if it is too noisy.
1286 if (Key.isExactProfile())
1287 DiagKind = diag::warn_arc_repeated_use_of_weak;
1289 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1291 // Classify the weak object being accessed for better warning text.
1292 // This enum should stay in sync with the cases in
1293 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1301 const NamedDecl *D = Key.getProperty();
1302 if (isa<VarDecl>(D))
1303 ObjectKind = Variable;
1304 else if (isa<ObjCPropertyDecl>(D))
1305 ObjectKind = Property;
1306 else if (isa<ObjCMethodDecl>(D))
1307 ObjectKind = ImplicitProperty;
1308 else if (isa<ObjCIvarDecl>(D))
1311 llvm_unreachable("Unexpected weak object kind!");
1313 // Show the first time the object was read.
1314 S.Diag(FirstRead->getLocStart(), DiagKind)
1315 << int(ObjectKind) << D << int(FunctionKind)
1316 << FirstRead->getSourceRange();
1318 // Print all the other accesses as notes.
1319 for (const auto &Use : Uses) {
1320 if (Use.getUseExpr() == FirstRead)
1322 S.Diag(Use.getUseExpr()->getLocStart(),
1323 diag::note_arc_weak_also_accessed_here)
1324 << Use.getUseExpr()->getSourceRange();
1330 class UninitValsDiagReporter : public UninitVariablesHandler {
1332 typedef SmallVector<UninitUse, 2> UsesVec;
1333 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1334 // Prefer using MapVector to DenseMap, so that iteration order will be
1335 // the same as insertion order. This is needed to obtain a deterministic
1336 // order of diagnostics when calling flushDiagnostics().
1337 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1341 UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
1342 ~UninitValsDiagReporter() {
1346 MappedType &getUses(const VarDecl *vd) {
1348 uses = new UsesMap();
1350 MappedType &V = (*uses)[vd];
1351 if (!V.getPointer())
1352 V.setPointer(new UsesVec());
1357 void handleUseOfUninitVariable(const VarDecl *vd,
1358 const UninitUse &use) override {
1359 getUses(vd).getPointer()->push_back(use);
1362 void handleSelfInit(const VarDecl *vd) override {
1363 getUses(vd).setInt(true);
1366 void flushDiagnostics() {
1370 for (const auto &P : *uses) {
1371 const VarDecl *vd = P.first;
1372 const MappedType &V = P.second;
1374 UsesVec *vec = V.getPointer();
1375 bool hasSelfInit = V.getInt();
1377 // Specially handle the case where we have uses of an uninitialized
1378 // variable, but the root cause is an idiomatic self-init. We want
1379 // to report the diagnostic at the self-init since that is the root cause.
1380 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1381 DiagnoseUninitializedUse(S, vd,
1382 UninitUse(vd->getInit()->IgnoreParenCasts(),
1383 /* isAlwaysUninit */ true),
1384 /* alwaysReportSelfInit */ true);
1386 // Sort the uses by their SourceLocations. While not strictly
1387 // guaranteed to produce them in line/column order, this will provide
1388 // a stable ordering.
1389 std::sort(vec->begin(), vec->end(),
1390 [](const UninitUse &a, const UninitUse &b) {
1391 // Prefer a more confident report over a less confident one.
1392 if (a.getKind() != b.getKind())
1393 return a.getKind() > b.getKind();
1394 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1397 for (const auto &U : *vec) {
1398 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1399 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1401 if (DiagnoseUninitializedUse(S, vd, Use))
1402 // Skip further diagnostics for this variable. We try to warn only
1403 // on the first point at which a variable is used uninitialized.
1408 // Release the uses vector.
1415 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1416 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1417 return U.getKind() == UninitUse::Always ||
1418 U.getKind() == UninitUse::AfterCall ||
1419 U.getKind() == UninitUse::AfterDecl;
1427 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1428 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1429 typedef std::list<DelayedDiag> DiagList;
1431 struct SortDiagBySourceLocation {
1433 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1435 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1436 // Although this call will be slow, this is only called when outputting
1437 // multiple warnings.
1438 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1443 //===----------------------------------------------------------------------===//
1445 //===----------------------------------------------------------------------===//
1447 namespace thread_safety {
1449 class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1452 SourceLocation FunLocation, FunEndLocation;
1455 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1456 SourceLocation Loc) {
1457 // Gracefully handle rare cases when the analysis can't get a more
1458 // precise source location.
1461 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1462 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1466 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1467 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
1469 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1470 /// We need to output diagnostics produced while iterating through
1471 /// the lockset in deterministic order, so this function orders diagnostics
1472 /// and outputs them.
1473 void emitDiagnostics() {
1474 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1475 for (const auto &Diag : Warnings) {
1476 S.Diag(Diag.first.first, Diag.first.second);
1477 for (const auto &Note : Diag.second)
1478 S.Diag(Note.first, Note.second);
1482 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1483 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1485 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1487 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1488 SourceLocation Loc) override {
1489 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1491 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1492 LockKind Expected, LockKind Received,
1493 SourceLocation Loc) override {
1494 if (Loc.isInvalid())
1496 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1497 << Kind << LockName << Received
1499 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1501 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1502 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1505 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1506 SourceLocation LocLocked,
1507 SourceLocation LocEndOfScope,
1508 LockErrorKind LEK) override {
1509 unsigned DiagID = 0;
1511 case LEK_LockedSomePredecessors:
1512 DiagID = diag::warn_lock_some_predecessors;
1514 case LEK_LockedSomeLoopIterations:
1515 DiagID = diag::warn_expecting_lock_held_on_loop;
1517 case LEK_LockedAtEndOfFunction:
1518 DiagID = diag::warn_no_unlock;
1520 case LEK_NotLockedAtEndOfFunction:
1521 DiagID = diag::warn_expecting_locked;
1524 if (LocEndOfScope.isInvalid())
1525 LocEndOfScope = FunEndLocation;
1527 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1529 if (LocLocked.isValid()) {
1530 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1532 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1535 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1538 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1539 SourceLocation Loc1,
1540 SourceLocation Loc2) override {
1541 PartialDiagnosticAt Warning(Loc1,
1542 S.PDiag(diag::warn_lock_exclusive_and_shared)
1543 << Kind << LockName);
1544 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1545 << Kind << LockName);
1546 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1549 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1550 ProtectedOperationKind POK, AccessKind AK,
1551 SourceLocation Loc) override {
1552 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1553 "Only works for variables");
1554 unsigned DiagID = POK == POK_VarAccess?
1555 diag::warn_variable_requires_any_lock:
1556 diag::warn_var_deref_requires_any_lock;
1557 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1558 << D->getNameAsString() << getLockKindFromAccessKind(AK));
1559 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1562 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1563 ProtectedOperationKind POK, Name LockName,
1564 LockKind LK, SourceLocation Loc,
1565 Name *PossibleMatch) override {
1566 unsigned DiagID = 0;
1567 if (PossibleMatch) {
1570 DiagID = diag::warn_variable_requires_lock_precise;
1572 case POK_VarDereference:
1573 DiagID = diag::warn_var_deref_requires_lock_precise;
1575 case POK_FunctionCall:
1576 DiagID = diag::warn_fun_requires_lock_precise;
1579 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1580 << D->getNameAsString()
1582 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1584 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1588 DiagID = diag::warn_variable_requires_lock;
1590 case POK_VarDereference:
1591 DiagID = diag::warn_var_deref_requires_lock;
1593 case POK_FunctionCall:
1594 DiagID = diag::warn_fun_requires_lock;
1597 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1598 << D->getNameAsString()
1600 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1604 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1605 SourceLocation Loc) override {
1606 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1607 << Kind << FunName << LockName);
1608 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1615 //===----------------------------------------------------------------------===//
1617 //===----------------------------------------------------------------------===//
1620 namespace consumed {
1622 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1629 ConsumedWarningsHandler(Sema &S) : S(S) {}
1631 void emitDiagnostics() override {
1632 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1633 for (const auto &Diag : Warnings) {
1634 S.Diag(Diag.first.first, Diag.first.second);
1635 for (const auto &Note : Diag.second)
1636 S.Diag(Note.first, Note.second);
1640 void warnLoopStateMismatch(SourceLocation Loc,
1641 StringRef VariableName) override {
1642 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1645 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1648 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1649 StringRef VariableName,
1650 StringRef ExpectedState,
1651 StringRef ObservedState) override {
1653 PartialDiagnosticAt Warning(Loc, S.PDiag(
1654 diag::warn_param_return_typestate_mismatch) << VariableName <<
1655 ExpectedState << ObservedState);
1657 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1660 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1661 StringRef ObservedState) override {
1663 PartialDiagnosticAt Warning(Loc, S.PDiag(
1664 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1666 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1669 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1670 StringRef TypeName) override {
1671 PartialDiagnosticAt Warning(Loc, S.PDiag(
1672 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1674 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1677 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1678 StringRef ObservedState) override {
1680 PartialDiagnosticAt Warning(Loc, S.PDiag(
1681 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1683 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1686 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1687 SourceLocation Loc) override {
1689 PartialDiagnosticAt Warning(Loc, S.PDiag(
1690 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1692 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1695 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1696 StringRef State, SourceLocation Loc) override {
1698 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1699 MethodName << VariableName << State);
1701 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1706 //===----------------------------------------------------------------------===//
1707 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1708 // warnings on a function, method, or block.
1709 //===----------------------------------------------------------------------===//
1711 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1712 enableCheckFallThrough = 1;
1713 enableCheckUnreachable = 0;
1714 enableThreadSafetyAnalysis = 0;
1715 enableConsumedAnalysis = 0;
1718 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1719 return (unsigned)!D.isIgnored(diag, SourceLocation());
1722 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1724 NumFunctionsAnalyzed(0),
1725 NumFunctionsWithBadCFGs(0),
1727 MaxCFGBlocksPerFunction(0),
1728 NumUninitAnalysisFunctions(0),
1729 NumUninitAnalysisVariables(0),
1730 MaxUninitAnalysisVariablesPerFunction(0),
1731 NumUninitAnalysisBlockVisits(0),
1732 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1734 using namespace diag;
1735 DiagnosticsEngine &D = S.getDiagnostics();
1737 DefaultPolicy.enableCheckUnreachable =
1738 isEnabled(D, warn_unreachable) ||
1739 isEnabled(D, warn_unreachable_break) ||
1740 isEnabled(D, warn_unreachable_return) ||
1741 isEnabled(D, warn_unreachable_loop_increment);
1743 DefaultPolicy.enableThreadSafetyAnalysis =
1744 isEnabled(D, warn_double_lock);
1746 DefaultPolicy.enableConsumedAnalysis =
1747 isEnabled(D, warn_use_in_invalid_state);
1750 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1751 for (const auto &D : fscope->PossiblyUnreachableDiags)
1752 S.Diag(D.Loc, D.PD);
1756 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1757 sema::FunctionScopeInfo *fscope,
1758 const Decl *D, const BlockExpr *blkExpr) {
1760 // We avoid doing analysis-based warnings when there are errors for
1762 // (1) The CFGs often can't be constructed (if the body is invalid), so
1763 // don't bother trying.
1764 // (2) The code already has problems; running the analysis just takes more
1766 DiagnosticsEngine &Diags = S.getDiagnostics();
1768 // Do not do any analysis for declarations in system headers if we are
1769 // going to just ignore them.
1770 if (Diags.getSuppressSystemWarnings() &&
1771 S.SourceMgr.isInSystemHeader(D->getLocation()))
1774 // For code in dependent contexts, we'll do this at instantiation time.
1775 if (cast<DeclContext>(D)->isDependentContext())
1778 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1779 // Flush out any possibly unreachable diagnostics.
1780 flushDiagnostics(S, fscope);
1784 const Stmt *Body = D->getBody();
1787 // Construct the analysis context with the specified CFG build options.
1788 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
1790 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1791 // explosion for destructors that can result and the compile time hit.
1792 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1793 AC.getCFGBuildOptions().AddEHEdges = false;
1794 AC.getCFGBuildOptions().AddInitializers = true;
1795 AC.getCFGBuildOptions().AddImplicitDtors = true;
1796 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1797 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
1799 // Force that certain expressions appear as CFGElements in the CFG. This
1800 // is used to speed up various analyses.
1801 // FIXME: This isn't the right factoring. This is here for initial
1802 // prototyping, but we need a way for analyses to say what expressions they
1803 // expect to always be CFGElements and then fill in the BuildOptions
1804 // appropriately. This is essentially a layering violation.
1805 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1806 P.enableConsumedAnalysis) {
1807 // Unreachable code analysis and thread safety require a linearized CFG.
1808 AC.getCFGBuildOptions().setAllAlwaysAdd();
1811 AC.getCFGBuildOptions()
1812 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1813 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1814 .setAlwaysAdd(Stmt::BlockExprClass)
1815 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1816 .setAlwaysAdd(Stmt::DeclRefExprClass)
1817 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1818 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1819 .setAlwaysAdd(Stmt::AttributedStmtClass);
1822 // Install the logical handler for -Wtautological-overlap-compare
1823 std::unique_ptr<LogicalErrorHandler> LEH;
1824 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1825 D->getLocStart())) {
1826 LEH.reset(new LogicalErrorHandler(S));
1827 AC.getCFGBuildOptions().Observer = LEH.get();
1830 // Emit delayed diagnostics.
1831 if (!fscope->PossiblyUnreachableDiags.empty()) {
1832 bool analyzed = false;
1834 // Register the expressions with the CFGBuilder.
1835 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1837 AC.registerForcedBlockExpression(D.stmt);
1842 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1843 bool processed = false;
1845 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
1846 CFGReverseBlockReachabilityAnalysis *cra =
1847 AC.getCFGReachablityAnalysis();
1848 // FIXME: We should be able to assert that block is non-null, but
1849 // the CFG analysis can skip potentially-evaluated expressions in
1850 // edge cases; see test/Sema/vla-2.c.
1852 // Can this block be reached from the entrance?
1853 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
1854 S.Diag(D.Loc, D.PD);
1859 // Emit the warning anyway if we cannot map to a basic block.
1860 S.Diag(D.Loc, D.PD);
1866 flushDiagnostics(S, fscope);
1870 // Warning: check missing 'return'
1871 if (P.enableCheckFallThrough) {
1872 const CheckFallThroughDiagnostics &CD =
1873 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
1874 : (isa<CXXMethodDecl>(D) &&
1875 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1876 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1877 ? CheckFallThroughDiagnostics::MakeForLambda()
1878 : CheckFallThroughDiagnostics::MakeForFunction(D));
1879 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
1882 // Warning: check for unreachable code
1883 if (P.enableCheckUnreachable) {
1884 // Only check for unreachable code on non-template instantiations.
1885 // Different template instantiations can effectively change the control-flow
1886 // and it is very difficult to prove that a snippet of code in a template
1887 // is unreachable for all instantiations.
1888 bool isTemplateInstantiation = false;
1889 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1890 isTemplateInstantiation = Function->isTemplateInstantiation();
1891 if (!isTemplateInstantiation)
1892 CheckUnreachable(S, AC);
1895 // Check for thread safety violations
1896 if (P.enableThreadSafetyAnalysis) {
1897 SourceLocation FL = AC.getDecl()->getLocation();
1898 SourceLocation FEL = AC.getDecl()->getLocEnd();
1899 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
1900 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
1901 Reporter.setIssueBetaWarnings(true);
1903 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1904 Reporter.emitDiagnostics();
1907 // Check for violations of consumed properties.
1908 if (P.enableConsumedAnalysis) {
1909 consumed::ConsumedWarningsHandler WarningHandler(S);
1910 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
1914 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
1915 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
1916 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
1917 if (CFG *cfg = AC.getCFG()) {
1918 UninitValsDiagReporter reporter(S);
1919 UninitVariablesAnalysisStats stats;
1920 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
1921 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
1924 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1925 ++NumUninitAnalysisFunctions;
1926 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1927 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1928 MaxUninitAnalysisVariablesPerFunction =
1929 std::max(MaxUninitAnalysisVariablesPerFunction,
1930 stats.NumVariablesAnalyzed);
1931 MaxUninitAnalysisBlockVisitsPerFunction =
1932 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1933 stats.NumBlockVisits);
1938 bool FallThroughDiagFull =
1939 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
1940 bool FallThroughDiagPerFunction = !Diags.isIgnored(
1941 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
1942 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
1943 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
1946 if (S.getLangOpts().ObjCARCWeak &&
1947 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
1948 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
1951 // Check for infinite self-recursion in functions
1952 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
1953 D->getLocStart())) {
1954 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1955 checkRecursiveFunction(S, FD, Body, AC);
1959 // If none of the previous checks caused a CFG build, trigger one here
1960 // for -Wtautological-overlap-compare
1961 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1962 D->getLocStart())) {
1966 // Collect statistics about the CFG if it was built.
1967 if (S.CollectStats && AC.isCFGBuilt()) {
1968 ++NumFunctionsAnalyzed;
1969 if (CFG *cfg = AC.getCFG()) {
1970 // If we successfully built a CFG for this context, record some more
1971 // detail information about it.
1972 NumCFGBlocks += cfg->getNumBlockIDs();
1973 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
1974 cfg->getNumBlockIDs());
1976 ++NumFunctionsWithBadCFGs;
1981 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1982 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1984 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1985 unsigned AvgCFGBlocksPerFunction =
1986 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1987 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1988 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1989 << " " << NumCFGBlocks << " CFG blocks built.\n"
1990 << " " << AvgCFGBlocksPerFunction
1991 << " average CFG blocks per function.\n"
1992 << " " << MaxCFGBlocksPerFunction
1993 << " max CFG blocks per function.\n";
1995 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1996 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1997 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1998 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1999 llvm::errs() << NumUninitAnalysisFunctions
2000 << " functions analyzed for uninitialiazed variables\n"
2001 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2002 << " " << AvgUninitVariablesPerFunction
2003 << " average variables per function.\n"
2004 << " " << MaxUninitAnalysisVariablesPerFunction
2005 << " max variables per function.\n"
2006 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2007 << " " << AvgUninitBlockVisitsPerFunction
2008 << " average block visits per function.\n"
2009 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2010 << " max block visits per function.\n";