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/AnalysisDeclContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/CFGStmtMap.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/MapVector.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/Support/Casting.h"
50 using namespace clang;
52 //===----------------------------------------------------------------------===//
53 // Unreachable code analysis.
54 //===----------------------------------------------------------------------===//
57 class UnreachableCodeHandler : public reachable_code::Callback {
59 SourceRange PreviousSilenceableCondVal;
62 UnreachableCodeHandler(Sema &s) : S(s) {}
64 void HandleUnreachable(reachable_code::UnreachableKind UK,
66 SourceRange SilenceableCondVal,
68 SourceRange R2) override {
69 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
75 PreviousSilenceableCondVal = SilenceableCondVal;
77 unsigned diag = diag::warn_unreachable;
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
82 case reachable_code::UK_Return:
83 diag = diag::warn_unreachable_return;
85 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
88 case reachable_code::UK_Other:
92 S.Diag(L, diag) << R1 << R2;
94 SourceLocation Open = SilenceableCondVal.getBegin();
96 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
98 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
106 } // anonymous namespace
108 /// CheckUnreachable - Check for unreachable code.
109 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
120 UnreachableCodeHandler UC(S);
121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
125 /// Warn on logical operator errors in CFGBuilder
126 class LogicalErrorHandler : public CFGCallback {
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
136 // Recurse to children.
137 for (const Stmt *SubStmt : E->children())
138 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
139 if (HasMacroID(SubExpr))
145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
164 } // anonymous namespace
166 //===----------------------------------------------------------------------===//
167 // Check for infinite self-recursion in functions
168 //===----------------------------------------------------------------------===//
170 // Returns true if the function is called anywhere within the CFGBlock.
171 // For member functions, the additional condition of being call from the
172 // this pointer is required.
173 static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
174 // Process all the Stmt's in this block to find any calls to FD.
175 for (const auto &B : Block) {
176 if (B.getKind() != CFGElement::Statement)
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
184 // Skip function calls which are qualified with a templated class.
185 if (const DeclRefExpr *DRE =
186 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
187 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
188 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
189 isa<TemplateSpecializationType>(NNS->getAsType())) {
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
203 // Returns true if every path from the entry block passes through a call to FD.
204 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
205 llvm::SmallPtrSet<CFGBlock *, 16> Visited;
206 llvm::SmallVector<CFGBlock *, 16> WorkList;
207 // Keep track of whether we found at least one recursive path.
208 bool foundRecursion = false;
210 const unsigned ExitID = cfg->getExit().getBlockID();
212 // Seed the work list with the entry block.
213 WorkList.push_back(&cfg->getEntry());
215 while (!WorkList.empty()) {
216 CFGBlock *Block = WorkList.pop_back_val();
218 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
219 if (CFGBlock *SuccBlock = *I) {
220 if (!Visited.insert(SuccBlock).second)
223 // Found a path to the exit node without a recursive call.
224 if (ExitID == SuccBlock->getBlockID())
227 // If the successor block contains a recursive call, end analysis there.
228 if (hasRecursiveCallInPath(FD, *SuccBlock)) {
229 foundRecursion = true;
233 WorkList.push_back(SuccBlock);
237 return foundRecursion;
240 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
241 const Stmt *Body, AnalysisDeclContext &AC) {
242 FD = FD->getCanonicalDecl();
244 // Only run on non-templated functions and non-templated members of
245 // templated classes.
246 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
247 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
250 CFG *cfg = AC.getCFG();
253 // Emit diagnostic if a recursive function call is detected for all paths.
254 if (checkForRecursiveFunctionCall(FD, cfg))
255 S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
258 //===----------------------------------------------------------------------===//
259 // Check for throw in a non-throwing function.
260 //===----------------------------------------------------------------------===//
262 /// Determine whether an exception thrown by E, unwinding from ThrowBlock,
263 /// can reach ExitBlock.
264 static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
266 SmallVector<CFGBlock *, 16> Stack;
267 llvm::BitVector Queued(Body->getNumBlockIDs());
269 Stack.push_back(&ThrowBlock);
270 Queued[ThrowBlock.getBlockID()] = true;
272 while (!Stack.empty()) {
273 CFGBlock &UnwindBlock = *Stack.back();
276 for (auto &Succ : UnwindBlock.succs()) {
277 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
280 if (Succ->getBlockID() == Body->getExit().getBlockID())
284 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
285 QualType Caught = Catch->getCaughtType();
286 if (Caught.isNull() || // catch (...) catches everything
287 !E->getSubExpr() || // throw; is considered cuaght by any handler
288 S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
289 // Exception doesn't escape via this path.
292 Stack.push_back(Succ);
293 Queued[Succ->getBlockID()] = true;
301 static void visitReachableThrows(
303 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
304 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
305 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
306 for (CFGBlock *B : *BodyCFG) {
307 if (!Reachable[B->getBlockID()])
309 for (CFGElement &E : *B) {
310 Optional<CFGStmt> S = E.getAs<CFGStmt>();
313 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
319 static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
320 const FunctionDecl *FD) {
321 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
322 FD->getTypeSourceInfo()) {
323 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
324 if (S.getLangOpts().CPlusPlus11 &&
325 (isa<CXXDestructorDecl>(FD) ||
326 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
327 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
328 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
329 getAs<FunctionProtoType>())
330 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
331 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
332 << FD->getExceptionSpecSourceRange();
334 S.Diag(FD->getLocation(), diag::note_throw_in_function)
335 << FD->getExceptionSpecSourceRange();
339 static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
340 AnalysisDeclContext &AC) {
341 CFG *BodyCFG = AC.getCFG();
344 if (BodyCFG->getExit().pred_empty())
346 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
347 if (throwEscapes(S, Throw, Block, BodyCFG))
348 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
352 static bool isNoexcept(const FunctionDecl *FD) {
353 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
354 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
359 //===----------------------------------------------------------------------===//
360 // Check for missing return value.
361 //===----------------------------------------------------------------------===//
363 enum ControlFlowKind {
368 NeverFallThroughOrReturn
371 /// CheckFallThrough - Check that we don't fall off the end of a
372 /// Statement that should return a value.
374 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
375 /// MaybeFallThrough iff we might or might not fall off the end,
376 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
377 /// return. We assume NeverFallThrough iff we never fall off the end of the
378 /// statement but we may return. We assume that functions not marked noreturn
380 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
381 CFG *cfg = AC.getCFG();
382 if (!cfg) return UnknownFallThrough;
384 // The CFG leaves in dead things, and we don't want the dead code paths to
385 // confuse us, so we mark all live things first.
386 llvm::BitVector live(cfg->getNumBlockIDs());
387 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
390 bool AddEHEdges = AC.getAddEHEdges();
391 if (!AddEHEdges && count != cfg->getNumBlockIDs())
392 // When there are things remaining dead, and we didn't add EH edges
393 // from CallExprs to the catch clauses, we have to go back and
394 // mark them as live.
395 for (const auto *B : *cfg) {
396 if (!live[B->getBlockID()]) {
397 if (B->pred_begin() == B->pred_end()) {
398 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
399 // When not adding EH edges from calls, catch clauses
400 // can otherwise seem dead. Avoid noting them as dead.
401 count += reachable_code::ScanReachableFromBlock(B, live);
407 // Now we know what is live, we check the live precessors of the exit block
408 // and look for fall through paths, being careful to ignore normal returns,
409 // and exceptional paths.
410 bool HasLiveReturn = false;
411 bool HasFakeEdge = false;
412 bool HasPlainEdge = false;
413 bool HasAbnormalEdge = false;
415 // Ignore default cases that aren't likely to be reachable because all
416 // enums in a switch(X) have explicit case statements.
417 CFGBlock::FilterOptions FO;
418 FO.IgnoreDefaultsWithCoveredEnums = 1;
420 for (CFGBlock::filtered_pred_iterator I =
421 cfg->getExit().filtered_pred_start_end(FO);
423 const CFGBlock &B = **I;
424 if (!live[B.getBlockID()])
427 // Skip blocks which contain an element marked as no-return. They don't
428 // represent actually viable edges into the exit block, so mark them as
430 if (B.hasNoReturnElement()) {
431 HasAbnormalEdge = true;
435 // Destructors can appear after the 'return' in the CFG. This is
436 // normal. We need to look pass the destructors for the return
437 // statement (if it exists).
438 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
440 for ( ; ri != re ; ++ri)
441 if (ri->getAs<CFGStmt>())
444 // No more CFGElements in the block?
446 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
447 HasAbnormalEdge = true;
450 // A labeled empty statement, or the entry block...
455 CFGStmt CS = ri->castAs<CFGStmt>();
456 const Stmt *S = CS.getStmt();
457 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
458 HasLiveReturn = true;
461 if (isa<ObjCAtThrowStmt>(S)) {
465 if (isa<CXXThrowExpr>(S)) {
469 if (isa<MSAsmStmt>(S)) {
470 // TODO: Verify this is correct.
472 HasLiveReturn = true;
475 if (isa<CXXTryStmt>(S)) {
476 HasAbnormalEdge = true;
479 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
481 HasAbnormalEdge = true;
489 return NeverFallThrough;
490 return NeverFallThroughOrReturn;
492 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
493 return MaybeFallThrough;
494 // This says AlwaysFallThrough for calls to functions that are not marked
495 // noreturn, that don't return. If people would like this warning to be more
496 // accurate, such functions should be marked as noreturn.
497 return AlwaysFallThrough;
502 struct CheckFallThroughDiagnostics {
503 unsigned diag_MaybeFallThrough_HasNoReturn;
504 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
505 unsigned diag_AlwaysFallThrough_HasNoReturn;
506 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
507 unsigned diag_NeverFallThroughOrReturn;
508 enum { Function, Block, Lambda, Coroutine } funMode;
509 SourceLocation FuncLoc;
511 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
512 CheckFallThroughDiagnostics D;
513 D.FuncLoc = Func->getLocation();
514 D.diag_MaybeFallThrough_HasNoReturn =
515 diag::warn_falloff_noreturn_function;
516 D.diag_MaybeFallThrough_ReturnsNonVoid =
517 diag::warn_maybe_falloff_nonvoid_function;
518 D.diag_AlwaysFallThrough_HasNoReturn =
519 diag::warn_falloff_noreturn_function;
520 D.diag_AlwaysFallThrough_ReturnsNonVoid =
521 diag::warn_falloff_nonvoid_function;
523 // Don't suggest that virtual functions be marked "noreturn", since they
524 // might be overridden by non-noreturn functions.
525 bool isVirtualMethod = false;
526 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
527 isVirtualMethod = Method->isVirtual();
529 // Don't suggest that template instantiations be marked "noreturn"
530 bool isTemplateInstantiation = false;
531 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
532 isTemplateInstantiation = Function->isTemplateInstantiation();
534 if (!isVirtualMethod && !isTemplateInstantiation)
535 D.diag_NeverFallThroughOrReturn =
536 diag::warn_suggest_noreturn_function;
538 D.diag_NeverFallThroughOrReturn = 0;
540 D.funMode = Function;
544 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
545 CheckFallThroughDiagnostics D;
546 D.FuncLoc = Func->getLocation();
547 D.diag_MaybeFallThrough_HasNoReturn = 0;
548 D.diag_MaybeFallThrough_ReturnsNonVoid =
549 diag::warn_maybe_falloff_nonvoid_coroutine;
550 D.diag_AlwaysFallThrough_HasNoReturn = 0;
551 D.diag_AlwaysFallThrough_ReturnsNonVoid =
552 diag::warn_falloff_nonvoid_coroutine;
553 D.funMode = Coroutine;
557 static CheckFallThroughDiagnostics MakeForBlock() {
558 CheckFallThroughDiagnostics D;
559 D.diag_MaybeFallThrough_HasNoReturn =
560 diag::err_noreturn_block_has_return_expr;
561 D.diag_MaybeFallThrough_ReturnsNonVoid =
562 diag::err_maybe_falloff_nonvoid_block;
563 D.diag_AlwaysFallThrough_HasNoReturn =
564 diag::err_noreturn_block_has_return_expr;
565 D.diag_AlwaysFallThrough_ReturnsNonVoid =
566 diag::err_falloff_nonvoid_block;
567 D.diag_NeverFallThroughOrReturn = 0;
572 static CheckFallThroughDiagnostics MakeForLambda() {
573 CheckFallThroughDiagnostics D;
574 D.diag_MaybeFallThrough_HasNoReturn =
575 diag::err_noreturn_lambda_has_return_expr;
576 D.diag_MaybeFallThrough_ReturnsNonVoid =
577 diag::warn_maybe_falloff_nonvoid_lambda;
578 D.diag_AlwaysFallThrough_HasNoReturn =
579 diag::err_noreturn_lambda_has_return_expr;
580 D.diag_AlwaysFallThrough_ReturnsNonVoid =
581 diag::warn_falloff_nonvoid_lambda;
582 D.diag_NeverFallThroughOrReturn = 0;
587 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
588 bool HasNoReturn) const {
589 if (funMode == Function) {
590 return (ReturnsVoid ||
591 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
594 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
597 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
599 if (funMode == Coroutine) {
600 return (ReturnsVoid ||
601 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
602 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
606 // For blocks / lambdas.
607 return ReturnsVoid && !HasNoReturn;
611 } // anonymous namespace
613 /// CheckFallThroughForBody - Check that we don't fall off the end of a
614 /// function that should return a value. Check that we don't fall off the end
615 /// of a noreturn function. We assume that functions and blocks not marked
616 /// noreturn will return.
617 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
618 const BlockExpr *blkExpr,
619 const CheckFallThroughDiagnostics &CD,
620 AnalysisDeclContext &AC,
621 sema::FunctionScopeInfo *FSI) {
623 bool ReturnsVoid = false;
624 bool HasNoReturn = false;
625 bool IsCoroutine = FSI->isCoroutine();
627 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
628 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
629 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
631 ReturnsVoid = FD->getReturnType()->isVoidType();
632 HasNoReturn = FD->isNoReturn();
634 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
635 ReturnsVoid = MD->getReturnType()->isVoidType();
636 HasNoReturn = MD->hasAttr<NoReturnAttr>();
638 else if (isa<BlockDecl>(D)) {
639 QualType BlockTy = blkExpr->getType();
640 if (const FunctionType *FT =
641 BlockTy->getPointeeType()->getAs<FunctionType>()) {
642 if (FT->getReturnType()->isVoidType())
644 if (FT->getNoReturnAttr())
649 DiagnosticsEngine &Diags = S.getDiagnostics();
651 // Short circuit for compilation speed.
652 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
654 SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
655 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
657 S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
662 // cpu_dispatch functions permit empty function bodies for ICC compatibility.
663 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
666 // Either in a function body compound statement, or a function-try-block.
667 switch (CheckFallThrough(AC)) {
668 case UnknownFallThrough:
671 case MaybeFallThrough:
673 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
674 else if (!ReturnsVoid)
675 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
677 case AlwaysFallThrough:
679 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
680 else if (!ReturnsVoid)
681 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
683 case NeverFallThroughOrReturn:
684 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
685 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
686 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
687 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
688 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
690 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
694 case NeverFallThrough:
699 //===----------------------------------------------------------------------===//
701 //===----------------------------------------------------------------------===//
704 /// ContainsReference - A visitor class to search for references to
705 /// a particular declaration (the needle) within any evaluated component of an
706 /// expression (recursively).
707 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
709 const DeclRefExpr *Needle;
712 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
714 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
715 : Inherited(Context), FoundReference(false), Needle(Needle) {}
717 void VisitExpr(const Expr *E) {
718 // Stop evaluating if we already have a reference.
722 Inherited::VisitExpr(E);
725 void VisitDeclRefExpr(const DeclRefExpr *E) {
727 FoundReference = true;
729 Inherited::VisitDeclRefExpr(E);
732 bool doesContainReference() const { return FoundReference; }
734 } // anonymous namespace
736 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
737 QualType VariableTy = VD->getType().getCanonicalType();
738 if (VariableTy->isBlockPointerType() &&
739 !VD->hasAttr<BlocksAttr>()) {
740 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
742 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
746 // Don't issue a fixit if there is already an initializer.
750 // Don't suggest a fixit inside macros.
751 if (VD->getEndLoc().isMacroID())
754 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
756 // Suggest possible initialization (if any).
757 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
761 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
762 << FixItHint::CreateInsertion(Loc, Init);
766 /// Create a fixit to remove an if-like statement, on the assumption that its
767 /// condition is CondVal.
768 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
769 const Stmt *Else, bool CondVal,
770 FixItHint &Fixit1, FixItHint &Fixit2) {
772 // If condition is always true, remove all but the 'then'.
773 Fixit1 = FixItHint::CreateRemoval(
774 CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
776 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
778 FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
781 // If condition is always false, remove all but the 'else'.
783 Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
784 If->getBeginLoc(), Else->getBeginLoc()));
786 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
790 /// DiagUninitUse -- Helper function to produce a diagnostic for an
791 /// uninitialized use of a variable.
792 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
793 bool IsCapturedByBlock) {
794 bool Diagnosed = false;
796 switch (Use.getKind()) {
797 case UninitUse::Always:
798 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
799 << VD->getDeclName() << IsCapturedByBlock
800 << Use.getUser()->getSourceRange();
803 case UninitUse::AfterDecl:
804 case UninitUse::AfterCall:
805 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
806 << VD->getDeclName() << IsCapturedByBlock
807 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
808 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
809 << VD->getSourceRange();
810 S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
811 << IsCapturedByBlock << Use.getUser()->getSourceRange();
814 case UninitUse::Maybe:
815 case UninitUse::Sometimes:
816 // Carry on to report sometimes-uninitialized branches, if possible,
817 // or a 'may be used uninitialized' diagnostic otherwise.
821 // Diagnose each branch which leads to a sometimes-uninitialized use.
822 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
824 assert(Use.getKind() == UninitUse::Sometimes);
826 const Expr *User = Use.getUser();
827 const Stmt *Term = I->Terminator;
829 // Information used when building the diagnostic.
834 // FixIts to suppress the diagnostic by removing the dead condition.
835 // For all binary terminators, branch 0 is taken if the condition is true,
836 // and branch 1 is taken if the condition is false.
837 int RemoveDiagKind = -1;
838 const char *FixitStr =
839 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
840 : (I->Output ? "1" : "0");
841 FixItHint Fixit1, Fixit2;
843 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
845 // Don't know how to report this. Just fall back to 'may be used
846 // uninitialized'. FIXME: Can this happen?
849 // "condition is true / condition is false".
850 case Stmt::IfStmtClass: {
851 const IfStmt *IS = cast<IfStmt>(Term);
854 Range = IS->getCond()->getSourceRange();
856 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
857 I->Output, Fixit1, Fixit2);
860 case Stmt::ConditionalOperatorClass: {
861 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
864 Range = CO->getCond()->getSourceRange();
866 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
867 I->Output, Fixit1, Fixit2);
870 case Stmt::BinaryOperatorClass: {
871 const BinaryOperator *BO = cast<BinaryOperator>(Term);
872 if (!BO->isLogicalOp())
875 Str = BO->getOpcodeStr();
876 Range = BO->getLHS()->getSourceRange();
878 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
879 (BO->getOpcode() == BO_LOr && !I->Output))
880 // true && y -> y, false || y -> y.
881 Fixit1 = FixItHint::CreateRemoval(
882 SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
884 // false && y -> false, true || y -> true.
885 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
889 // "loop is entered / loop is exited".
890 case Stmt::WhileStmtClass:
893 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
895 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
897 case Stmt::ForStmtClass:
900 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
903 Fixit1 = FixItHint::CreateRemoval(Range);
905 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
907 case Stmt::CXXForRangeStmtClass:
908 if (I->Output == 1) {
909 // The use occurs if a range-based for loop's body never executes.
910 // That may be impossible, and there's no syntactic fix for this,
911 // so treat it as a 'may be uninitialized' case.
916 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
919 // "condition is true / loop is exited".
920 case Stmt::DoStmtClass:
923 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
925 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
928 // "switch case is taken".
929 case Stmt::CaseStmtClass:
932 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
934 case Stmt::DefaultStmtClass:
937 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
941 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
942 << VD->getDeclName() << IsCapturedByBlock << DiagKind
943 << Str << I->Output << Range;
944 S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
945 << IsCapturedByBlock << User->getSourceRange();
946 if (RemoveDiagKind != -1)
947 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
948 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
954 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
955 << VD->getDeclName() << IsCapturedByBlock
956 << Use.getUser()->getSourceRange();
959 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
960 /// uninitialized variable. This manages the different forms of diagnostic
961 /// emitted for particular types of uses. Returns true if the use was diagnosed
962 /// as a warning. If a particular use is one we omit warnings for, returns
964 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
965 const UninitUse &Use,
966 bool alwaysReportSelfInit = false) {
967 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
968 // Inspect the initializer of the variable declaration which is
969 // being referenced prior to its initialization. We emit
970 // specialized diagnostics for self-initialization, and we
971 // specifically avoid warning about self references which take the
976 // This is used to indicate to GCC that 'x' is intentionally left
977 // uninitialized. Proven code paths which access 'x' in
978 // an uninitialized state after this will still warn.
979 if (const Expr *Initializer = VD->getInit()) {
980 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
983 ContainsReference CR(S.Context, DRE);
984 CR.Visit(Initializer);
985 if (CR.doesContainReference()) {
986 S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
987 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
992 DiagUninitUse(S, VD, Use, false);
994 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
995 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
996 S.Diag(BE->getBeginLoc(),
997 diag::warn_uninit_byref_blockvar_captured_by_block)
998 << VD->getDeclName();
1000 DiagUninitUse(S, VD, Use, true);
1003 // Report where the variable was declared when the use wasn't within
1004 // the initializer of that declaration & we didn't already suggest
1005 // an initialization fixit.
1006 if (!SuggestInitializationFixit(S, VD))
1007 S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
1008 << VD->getDeclName();
1014 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1016 FallthroughMapper(Sema &S)
1017 : FoundSwitchStatements(false),
1021 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1023 void markFallthroughVisited(const AttributedStmt *Stmt) {
1024 bool Found = FallthroughStmts.erase(Stmt);
1029 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1031 const AttrStmts &getFallthroughStmts() const {
1032 return FallthroughStmts;
1035 void fillReachableBlocks(CFG *Cfg) {
1036 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1037 std::deque<const CFGBlock *> BlockQueue;
1039 ReachableBlocks.insert(&Cfg->getEntry());
1040 BlockQueue.push_back(&Cfg->getEntry());
1041 // Mark all case blocks reachable to avoid problems with switching on
1042 // constants, covered enums, etc.
1043 // These blocks can contain fall-through annotations, and we don't want to
1044 // issue a warn_fallthrough_attr_unreachable for them.
1045 for (const auto *B : *Cfg) {
1046 const Stmt *L = B->getLabel();
1047 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
1048 BlockQueue.push_back(B);
1051 while (!BlockQueue.empty()) {
1052 const CFGBlock *P = BlockQueue.front();
1053 BlockQueue.pop_front();
1054 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1057 if (*I && ReachableBlocks.insert(*I).second)
1058 BlockQueue.push_back(*I);
1063 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1064 bool IsTemplateInstantiation) {
1065 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1067 int UnannotatedCnt = 0;
1070 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
1071 while (!BlockQueue.empty()) {
1072 const CFGBlock *P = BlockQueue.front();
1073 BlockQueue.pop_front();
1076 const Stmt *Term = P->getTerminator();
1077 if (Term && isa<SwitchStmt>(Term))
1078 continue; // Switch statement, good.
1080 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1081 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1082 continue; // Previous case label has no statements, good.
1084 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1085 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1086 continue; // Case label is preceded with a normal label, good.
1088 if (!ReachableBlocks.count(P)) {
1089 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1090 ElemEnd = P->rend();
1091 ElemIt != ElemEnd; ++ElemIt) {
1092 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1093 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1094 // Don't issue a warning for an unreachable fallthrough
1095 // attribute in template instantiations as it may not be
1096 // unreachable in all instantiations of the template.
1097 if (!IsTemplateInstantiation)
1098 S.Diag(AS->getBeginLoc(),
1099 diag::warn_fallthrough_attr_unreachable);
1100 markFallthroughVisited(AS);
1104 // Don't care about other unreachable statements.
1107 // If there are no unreachable statements, this may be a special
1110 // A a; // A has a destructor.
1113 // // <<<< This place is represented by a 'hanging' CFG block.
1118 const Stmt *LastStmt = getLastStmt(*P);
1119 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1120 markFallthroughVisited(AS);
1122 continue; // Fallthrough annotation, good.
1125 if (!LastStmt) { // This block contains no executable statements.
1126 // Traverse its predecessors.
1127 std::copy(P->pred_begin(), P->pred_end(),
1128 std::back_inserter(BlockQueue));
1134 return !!UnannotatedCnt;
1137 // RecursiveASTVisitor setup.
1138 bool shouldWalkTypesOfTypeLocs() const { return false; }
1140 bool VisitAttributedStmt(AttributedStmt *S) {
1141 if (asFallThroughAttr(S))
1142 FallthroughStmts.insert(S);
1146 bool VisitSwitchStmt(SwitchStmt *S) {
1147 FoundSwitchStatements = true;
1151 // We don't want to traverse local type declarations. We analyze their
1152 // methods separately.
1153 bool TraverseDecl(Decl *D) { return true; }
1155 // We analyze lambda bodies separately. Skip them here.
1156 bool TraverseLambdaExpr(LambdaExpr *LE) {
1157 // Traverse the captures, but not the body.
1158 for (const auto &C : zip(LE->captures(), LE->capture_inits()))
1159 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
1165 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1166 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1167 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1173 static const Stmt *getLastStmt(const CFGBlock &B) {
1174 if (const Stmt *Term = B.getTerminator())
1176 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1178 ElemIt != ElemEnd; ++ElemIt) {
1179 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1180 return CS->getStmt();
1182 // Workaround to detect a statement thrown out by CFGBuilder:
1183 // case X: {} case Y:
1184 // case X: ; case Y:
1185 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1186 if (!isa<SwitchCase>(SW->getSubStmt()))
1187 return SW->getSubStmt();
1192 bool FoundSwitchStatements;
1193 AttrStmts FallthroughStmts;
1195 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1197 } // anonymous namespace
1199 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1200 SourceLocation Loc) {
1201 TokenValue FallthroughTokens[] = {
1202 tok::l_square, tok::l_square,
1203 PP.getIdentifierInfo("fallthrough"),
1204 tok::r_square, tok::r_square
1207 TokenValue ClangFallthroughTokens[] = {
1208 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1209 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1210 tok::r_square, tok::r_square
1213 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
1215 StringRef MacroName;
1216 if (PreferClangAttr)
1217 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1218 if (MacroName.empty())
1219 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1220 if (MacroName.empty() && !PreferClangAttr)
1221 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1222 if (MacroName.empty())
1223 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1227 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1229 // Only perform this analysis when using [[]] attributes. There is no good
1230 // workflow for this warning when not using C++11. There is no good way to
1231 // silence the warning (no attribute is available) unless we are using
1232 // [[]] attributes. One could use pragmas to silence the warning, but as a
1233 // general solution that is gross and not in the spirit of this warning.
1235 // NOTE: This an intermediate solution. There are on-going discussions on
1236 // how to properly support this warning outside of C++11 with an annotation.
1237 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
1240 FallthroughMapper FM(S);
1241 FM.TraverseStmt(AC.getBody());
1243 if (!FM.foundSwitchStatements())
1246 if (PerFunction && FM.getFallthroughStmts().empty())
1249 CFG *Cfg = AC.getCFG();
1254 FM.fillReachableBlocks(Cfg);
1256 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1257 const Stmt *Label = B->getLabel();
1259 if (!Label || !isa<SwitchCase>(Label))
1264 bool IsTemplateInstantiation = false;
1265 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1266 IsTemplateInstantiation = Function->isTemplateInstantiation();
1267 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1268 IsTemplateInstantiation))
1271 S.Diag(Label->getBeginLoc(),
1272 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1273 : diag::warn_unannotated_fallthrough);
1275 if (!AnnotatedCnt) {
1276 SourceLocation L = Label->getBeginLoc();
1279 if (S.getLangOpts().CPlusPlus11) {
1280 const Stmt *Term = B->getTerminator();
1281 // Skip empty cases.
1282 while (B->empty() && !Term && B->succ_size() == 1) {
1283 B = *B->succ_begin();
1284 Term = B->getTerminator();
1286 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1287 Preprocessor &PP = S.getPreprocessor();
1288 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1289 SmallString<64> TextToInsert(AnnotationSpelling);
1290 TextToInsert += "; ";
1291 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1292 AnnotationSpelling <<
1293 FixItHint::CreateInsertion(L, TextToInsert);
1296 S.Diag(L, diag::note_insert_break_fixit) <<
1297 FixItHint::CreateInsertion(L, "break; ");
1301 for (const auto *F : FM.getFallthroughStmts())
1302 S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
1305 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1310 switch (S->getStmtClass()) {
1311 case Stmt::ForStmtClass:
1312 case Stmt::WhileStmtClass:
1313 case Stmt::CXXForRangeStmtClass:
1314 case Stmt::ObjCForCollectionStmtClass:
1316 case Stmt::DoStmtClass: {
1317 Expr::EvalResult Result;
1318 if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx))
1320 return Result.Val.getInt().getBoolValue();
1325 } while ((S = PM.getParent(S)));
1330 static void diagnoseRepeatedUseOfWeak(Sema &S,
1331 const sema::FunctionScopeInfo *CurFn,
1333 const ParentMap &PM) {
1334 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1335 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1336 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1337 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1340 ASTContext &Ctx = S.getASTContext();
1342 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1344 // Extract all weak objects that are referenced more than once.
1345 SmallVector<StmtUsesPair, 8> UsesByStmt;
1346 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1348 const WeakUseVector &Uses = I->second;
1350 // Find the first read of the weak object.
1351 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1352 for ( ; UI != UE; ++UI) {
1357 // If there were only writes to this object, don't warn.
1361 // If there was only one read, followed by any number of writes, and the
1362 // read is not within a loop, don't warn. Additionally, don't warn in a
1363 // loop if the base object is a local variable -- local variables are often
1364 // changed in loops.
1365 if (UI == Uses.begin()) {
1366 WeakUseVector::const_iterator UI2 = UI;
1367 for (++UI2; UI2 != UE; ++UI2)
1368 if (UI2->isUnsafe())
1372 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1375 const WeakObjectProfileTy &Profile = I->first;
1376 if (!Profile.isExactProfile())
1379 const NamedDecl *Base = Profile.getBase();
1381 Base = Profile.getProperty();
1382 assert(Base && "A profile always has a base or property.");
1384 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1385 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1390 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1393 if (UsesByStmt.empty())
1396 // Sort by first use so that we emit the warnings in a deterministic order.
1397 SourceManager &SM = S.getSourceManager();
1398 llvm::sort(UsesByStmt,
1399 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1400 return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
1401 RHS.first->getBeginLoc());
1404 // Classify the current code body for better warning text.
1405 // This enum should stay in sync with the cases in
1406 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1407 // FIXME: Should we use a common classification enum and the same set of
1408 // possibilities all throughout Sema?
1416 if (isa<sema::BlockScopeInfo>(CurFn))
1417 FunctionKind = Block;
1418 else if (isa<sema::LambdaScopeInfo>(CurFn))
1419 FunctionKind = Lambda;
1420 else if (isa<ObjCMethodDecl>(D))
1421 FunctionKind = Method;
1423 FunctionKind = Function;
1425 // Iterate through the sorted problems and emit warnings for each.
1426 for (const auto &P : UsesByStmt) {
1427 const Stmt *FirstRead = P.first;
1428 const WeakObjectProfileTy &Key = P.second->first;
1429 const WeakUseVector &Uses = P.second->second;
1431 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1432 // may not contain enough information to determine that these are different
1433 // properties. We can only be 100% sure of a repeated use in certain cases,
1434 // and we adjust the diagnostic kind accordingly so that the less certain
1435 // case can be turned off if it is too noisy.
1437 if (Key.isExactProfile())
1438 DiagKind = diag::warn_arc_repeated_use_of_weak;
1440 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1442 // Classify the weak object being accessed for better warning text.
1443 // This enum should stay in sync with the cases in
1444 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1452 const NamedDecl *KeyProp = Key.getProperty();
1453 if (isa<VarDecl>(KeyProp))
1454 ObjectKind = Variable;
1455 else if (isa<ObjCPropertyDecl>(KeyProp))
1456 ObjectKind = Property;
1457 else if (isa<ObjCMethodDecl>(KeyProp))
1458 ObjectKind = ImplicitProperty;
1459 else if (isa<ObjCIvarDecl>(KeyProp))
1462 llvm_unreachable("Unexpected weak object kind!");
1464 // Do not warn about IBOutlet weak property receivers being set to null
1465 // since they are typically only used from the main thread.
1466 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1467 if (Prop->hasAttr<IBOutletAttr>())
1470 // Show the first time the object was read.
1471 S.Diag(FirstRead->getBeginLoc(), DiagKind)
1472 << int(ObjectKind) << KeyProp << int(FunctionKind)
1473 << FirstRead->getSourceRange();
1475 // Print all the other accesses as notes.
1476 for (const auto &Use : Uses) {
1477 if (Use.getUseExpr() == FirstRead)
1479 S.Diag(Use.getUseExpr()->getBeginLoc(),
1480 diag::note_arc_weak_also_accessed_here)
1481 << Use.getUseExpr()->getSourceRange();
1487 class UninitValsDiagReporter : public UninitVariablesHandler {
1489 typedef SmallVector<UninitUse, 2> UsesVec;
1490 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1491 // Prefer using MapVector to DenseMap, so that iteration order will be
1492 // the same as insertion order. This is needed to obtain a deterministic
1493 // order of diagnostics when calling flushDiagnostics().
1494 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1498 UninitValsDiagReporter(Sema &S) : S(S) {}
1499 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1501 MappedType &getUses(const VarDecl *vd) {
1502 MappedType &V = uses[vd];
1503 if (!V.getPointer())
1504 V.setPointer(new UsesVec());
1508 void handleUseOfUninitVariable(const VarDecl *vd,
1509 const UninitUse &use) override {
1510 getUses(vd).getPointer()->push_back(use);
1513 void handleSelfInit(const VarDecl *vd) override {
1514 getUses(vd).setInt(true);
1517 void flushDiagnostics() {
1518 for (const auto &P : uses) {
1519 const VarDecl *vd = P.first;
1520 const MappedType &V = P.second;
1522 UsesVec *vec = V.getPointer();
1523 bool hasSelfInit = V.getInt();
1525 // Specially handle the case where we have uses of an uninitialized
1526 // variable, but the root cause is an idiomatic self-init. We want
1527 // to report the diagnostic at the self-init since that is the root cause.
1528 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1529 DiagnoseUninitializedUse(S, vd,
1530 UninitUse(vd->getInit()->IgnoreParenCasts(),
1531 /* isAlwaysUninit */ true),
1532 /* alwaysReportSelfInit */ true);
1534 // Sort the uses by their SourceLocations. While not strictly
1535 // guaranteed to produce them in line/column order, this will provide
1536 // a stable ordering.
1537 llvm::sort(vec->begin(), vec->end(),
1538 [](const UninitUse &a, const UninitUse &b) {
1539 // Prefer a more confident report over a less confident one.
1540 if (a.getKind() != b.getKind())
1541 return a.getKind() > b.getKind();
1542 return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
1545 for (const auto &U : *vec) {
1546 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1547 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1549 if (DiagnoseUninitializedUse(S, vd, Use))
1550 // Skip further diagnostics for this variable. We try to warn only
1551 // on the first point at which a variable is used uninitialized.
1556 // Release the uses vector.
1564 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1565 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1566 return U.getKind() == UninitUse::Always ||
1567 U.getKind() == UninitUse::AfterCall ||
1568 U.getKind() == UninitUse::AfterDecl;
1572 } // anonymous namespace
1576 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1577 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1578 typedef std::list<DelayedDiag> DiagList;
1580 struct SortDiagBySourceLocation {
1582 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1584 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1585 // Although this call will be slow, this is only called when outputting
1586 // multiple warnings.
1587 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1590 } // anonymous namespace
1591 } // namespace clang
1593 //===----------------------------------------------------------------------===//
1595 //===----------------------------------------------------------------------===//
1597 namespace threadSafety {
1599 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1602 SourceLocation FunLocation, FunEndLocation;
1604 const FunctionDecl *CurrentFunction;
1607 OptionalNotes getNotes() const {
1608 if (Verbose && CurrentFunction) {
1609 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1610 S.PDiag(diag::note_thread_warning_in_fun)
1611 << CurrentFunction);
1612 return OptionalNotes(1, FNote);
1614 return OptionalNotes();
1617 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1618 OptionalNotes ONS(1, Note);
1619 if (Verbose && CurrentFunction) {
1620 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1621 S.PDiag(diag::note_thread_warning_in_fun)
1622 << CurrentFunction);
1623 ONS.push_back(std::move(FNote));
1628 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1629 const PartialDiagnosticAt &Note2) const {
1631 ONS.push_back(Note1);
1632 ONS.push_back(Note2);
1633 if (Verbose && CurrentFunction) {
1634 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1635 S.PDiag(diag::note_thread_warning_in_fun)
1636 << CurrentFunction);
1637 ONS.push_back(std::move(FNote));
1643 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1644 SourceLocation Loc) {
1645 // Gracefully handle rare cases when the analysis can't get a more
1646 // precise source location.
1649 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1650 Warnings.emplace_back(std::move(Warning), getNotes());
1654 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1655 : S(S), FunLocation(FL), FunEndLocation(FEL),
1656 CurrentFunction(nullptr), Verbose(false) {}
1658 void setVerbose(bool b) { Verbose = b; }
1660 /// Emit all buffered diagnostics in order of sourcelocation.
1661 /// We need to output diagnostics produced while iterating through
1662 /// the lockset in deterministic order, so this function orders diagnostics
1663 /// and outputs them.
1664 void emitDiagnostics() {
1665 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1666 for (const auto &Diag : Warnings) {
1667 S.Diag(Diag.first.first, Diag.first.second);
1668 for (const auto &Note : Diag.second)
1669 S.Diag(Note.first, Note.second);
1673 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1674 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1676 Warnings.emplace_back(std::move(Warning), getNotes());
1679 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1680 SourceLocation Loc) override {
1681 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1684 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1685 LockKind Expected, LockKind Received,
1686 SourceLocation Loc) override {
1687 if (Loc.isInvalid())
1689 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1690 << Kind << LockName << Received
1692 Warnings.emplace_back(std::move(Warning), getNotes());
1695 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1696 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1699 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1700 SourceLocation LocLocked,
1701 SourceLocation LocEndOfScope,
1702 LockErrorKind LEK) override {
1703 unsigned DiagID = 0;
1705 case LEK_LockedSomePredecessors:
1706 DiagID = diag::warn_lock_some_predecessors;
1708 case LEK_LockedSomeLoopIterations:
1709 DiagID = diag::warn_expecting_lock_held_on_loop;
1711 case LEK_LockedAtEndOfFunction:
1712 DiagID = diag::warn_no_unlock;
1714 case LEK_NotLockedAtEndOfFunction:
1715 DiagID = diag::warn_expecting_locked;
1718 if (LocEndOfScope.isInvalid())
1719 LocEndOfScope = FunEndLocation;
1721 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1723 if (LocLocked.isValid()) {
1724 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1726 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1729 Warnings.emplace_back(std::move(Warning), getNotes());
1732 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1733 SourceLocation Loc1,
1734 SourceLocation Loc2) override {
1735 PartialDiagnosticAt Warning(Loc1,
1736 S.PDiag(diag::warn_lock_exclusive_and_shared)
1737 << Kind << LockName);
1738 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1739 << Kind << LockName);
1740 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1743 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1744 ProtectedOperationKind POK, AccessKind AK,
1745 SourceLocation Loc) override {
1746 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1747 "Only works for variables");
1748 unsigned DiagID = POK == POK_VarAccess?
1749 diag::warn_variable_requires_any_lock:
1750 diag::warn_var_deref_requires_any_lock;
1751 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1752 << D << getLockKindFromAccessKind(AK));
1753 Warnings.emplace_back(std::move(Warning), getNotes());
1756 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1757 ProtectedOperationKind POK, Name LockName,
1758 LockKind LK, SourceLocation Loc,
1759 Name *PossibleMatch) override {
1760 unsigned DiagID = 0;
1761 if (PossibleMatch) {
1764 DiagID = diag::warn_variable_requires_lock_precise;
1766 case POK_VarDereference:
1767 DiagID = diag::warn_var_deref_requires_lock_precise;
1769 case POK_FunctionCall:
1770 DiagID = diag::warn_fun_requires_lock_precise;
1773 DiagID = diag::warn_guarded_pass_by_reference;
1775 case POK_PtPassByRef:
1776 DiagID = diag::warn_pt_guarded_pass_by_reference;
1779 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1782 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1784 if (Verbose && POK == POK_VarAccess) {
1785 PartialDiagnosticAt VNote(D->getLocation(),
1786 S.PDiag(diag::note_guarded_by_declared_here)
1787 << D->getNameAsString());
1788 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1790 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1794 DiagID = diag::warn_variable_requires_lock;
1796 case POK_VarDereference:
1797 DiagID = diag::warn_var_deref_requires_lock;
1799 case POK_FunctionCall:
1800 DiagID = diag::warn_fun_requires_lock;
1803 DiagID = diag::warn_guarded_pass_by_reference;
1805 case POK_PtPassByRef:
1806 DiagID = diag::warn_pt_guarded_pass_by_reference;
1809 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1812 if (Verbose && POK == POK_VarAccess) {
1813 PartialDiagnosticAt Note(D->getLocation(),
1814 S.PDiag(diag::note_guarded_by_declared_here));
1815 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1817 Warnings.emplace_back(std::move(Warning), getNotes());
1821 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1822 SourceLocation Loc) override {
1823 PartialDiagnosticAt Warning(Loc,
1824 S.PDiag(diag::warn_acquire_requires_negative_cap)
1825 << Kind << LockName << Neg);
1826 Warnings.emplace_back(std::move(Warning), getNotes());
1829 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1830 SourceLocation Loc) override {
1831 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1832 << Kind << FunName << LockName);
1833 Warnings.emplace_back(std::move(Warning), getNotes());
1836 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1837 SourceLocation Loc) override {
1838 PartialDiagnosticAt Warning(Loc,
1839 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1840 Warnings.emplace_back(std::move(Warning), getNotes());
1843 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1844 PartialDiagnosticAt Warning(Loc,
1845 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1846 Warnings.emplace_back(std::move(Warning), getNotes());
1849 void enterFunction(const FunctionDecl* FD) override {
1850 CurrentFunction = FD;
1853 void leaveFunction(const FunctionDecl* FD) override {
1854 CurrentFunction = nullptr;
1857 } // anonymous namespace
1858 } // namespace threadSafety
1859 } // namespace clang
1861 //===----------------------------------------------------------------------===//
1863 //===----------------------------------------------------------------------===//
1866 namespace consumed {
1868 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1875 ConsumedWarningsHandler(Sema &S) : S(S) {}
1877 void emitDiagnostics() override {
1878 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1879 for (const auto &Diag : Warnings) {
1880 S.Diag(Diag.first.first, Diag.first.second);
1881 for (const auto &Note : Diag.second)
1882 S.Diag(Note.first, Note.second);
1886 void warnLoopStateMismatch(SourceLocation Loc,
1887 StringRef VariableName) override {
1888 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1891 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1894 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1895 StringRef VariableName,
1896 StringRef ExpectedState,
1897 StringRef ObservedState) override {
1899 PartialDiagnosticAt Warning(Loc, S.PDiag(
1900 diag::warn_param_return_typestate_mismatch) << VariableName <<
1901 ExpectedState << ObservedState);
1903 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1906 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1907 StringRef ObservedState) override {
1909 PartialDiagnosticAt Warning(Loc, S.PDiag(
1910 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1912 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1915 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1916 StringRef TypeName) override {
1917 PartialDiagnosticAt Warning(Loc, S.PDiag(
1918 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1920 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1923 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1924 StringRef ObservedState) override {
1926 PartialDiagnosticAt Warning(Loc, S.PDiag(
1927 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1929 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1932 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1933 SourceLocation Loc) override {
1935 PartialDiagnosticAt Warning(Loc, S.PDiag(
1936 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1938 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1941 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1942 StringRef State, SourceLocation Loc) override {
1944 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1945 MethodName << VariableName << State);
1947 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1950 } // anonymous namespace
1951 } // namespace consumed
1952 } // namespace clang
1954 //===----------------------------------------------------------------------===//
1955 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1956 // warnings on a function, method, or block.
1957 //===----------------------------------------------------------------------===//
1959 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1960 enableCheckFallThrough = 1;
1961 enableCheckUnreachable = 0;
1962 enableThreadSafetyAnalysis = 0;
1963 enableConsumedAnalysis = 0;
1966 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1967 return (unsigned)!D.isIgnored(diag, SourceLocation());
1970 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1972 NumFunctionsAnalyzed(0),
1973 NumFunctionsWithBadCFGs(0),
1975 MaxCFGBlocksPerFunction(0),
1976 NumUninitAnalysisFunctions(0),
1977 NumUninitAnalysisVariables(0),
1978 MaxUninitAnalysisVariablesPerFunction(0),
1979 NumUninitAnalysisBlockVisits(0),
1980 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1982 using namespace diag;
1983 DiagnosticsEngine &D = S.getDiagnostics();
1985 DefaultPolicy.enableCheckUnreachable =
1986 isEnabled(D, warn_unreachable) ||
1987 isEnabled(D, warn_unreachable_break) ||
1988 isEnabled(D, warn_unreachable_return) ||
1989 isEnabled(D, warn_unreachable_loop_increment);
1991 DefaultPolicy.enableThreadSafetyAnalysis =
1992 isEnabled(D, warn_double_lock);
1994 DefaultPolicy.enableConsumedAnalysis =
1995 isEnabled(D, warn_use_in_invalid_state);
1998 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1999 for (const auto &D : fscope->PossiblyUnreachableDiags)
2000 S.Diag(D.Loc, D.PD);
2004 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
2005 sema::FunctionScopeInfo *fscope,
2006 const Decl *D, const BlockExpr *blkExpr) {
2008 // We avoid doing analysis-based warnings when there are errors for
2010 // (1) The CFGs often can't be constructed (if the body is invalid), so
2011 // don't bother trying.
2012 // (2) The code already has problems; running the analysis just takes more
2014 DiagnosticsEngine &Diags = S.getDiagnostics();
2016 // Do not do any analysis if we are going to just ignore them.
2017 if (Diags.getIgnoreAllWarnings() ||
2018 (Diags.getSuppressSystemWarnings() &&
2019 S.SourceMgr.isInSystemHeader(D->getLocation())))
2022 // For code in dependent contexts, we'll do this at instantiation time.
2023 if (cast<DeclContext>(D)->isDependentContext())
2026 if (Diags.hasUncompilableErrorOccurred()) {
2027 // Flush out any possibly unreachable diagnostics.
2028 flushDiagnostics(S, fscope);
2032 const Stmt *Body = D->getBody();
2035 // Construct the analysis context with the specified CFG build options.
2036 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
2038 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
2039 // explosion for destructors that can result and the compile time hit.
2040 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2041 AC.getCFGBuildOptions().AddEHEdges = false;
2042 AC.getCFGBuildOptions().AddInitializers = true;
2043 AC.getCFGBuildOptions().AddImplicitDtors = true;
2044 AC.getCFGBuildOptions().AddTemporaryDtors = true;
2045 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
2046 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
2048 // Force that certain expressions appear as CFGElements in the CFG. This
2049 // is used to speed up various analyses.
2050 // FIXME: This isn't the right factoring. This is here for initial
2051 // prototyping, but we need a way for analyses to say what expressions they
2052 // expect to always be CFGElements and then fill in the BuildOptions
2053 // appropriately. This is essentially a layering violation.
2054 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2055 P.enableConsumedAnalysis) {
2056 // Unreachable code analysis and thread safety require a linearized CFG.
2057 AC.getCFGBuildOptions().setAllAlwaysAdd();
2060 AC.getCFGBuildOptions()
2061 .setAlwaysAdd(Stmt::BinaryOperatorClass)
2062 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
2063 .setAlwaysAdd(Stmt::BlockExprClass)
2064 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2065 .setAlwaysAdd(Stmt::DeclRefExprClass)
2066 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
2067 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2068 .setAlwaysAdd(Stmt::AttributedStmtClass);
2071 // Install the logical handler for -Wtautological-overlap-compare
2072 llvm::Optional<LogicalErrorHandler> LEH;
2073 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2074 D->getBeginLoc())) {
2076 AC.getCFGBuildOptions().Observer = &*LEH;
2079 // Emit delayed diagnostics.
2080 if (!fscope->PossiblyUnreachableDiags.empty()) {
2081 bool analyzed = false;
2083 // Register the expressions with the CFGBuilder.
2084 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2086 AC.registerForcedBlockExpression(D.stmt);
2091 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2092 bool processed = false;
2094 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
2095 CFGReverseBlockReachabilityAnalysis *cra =
2096 AC.getCFGReachablityAnalysis();
2097 // FIXME: We should be able to assert that block is non-null, but
2098 // the CFG analysis can skip potentially-evaluated expressions in
2099 // edge cases; see test/Sema/vla-2.c.
2101 // Can this block be reached from the entrance?
2102 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
2103 S.Diag(D.Loc, D.PD);
2108 // Emit the warning anyway if we cannot map to a basic block.
2109 S.Diag(D.Loc, D.PD);
2115 flushDiagnostics(S, fscope);
2118 // Warning: check missing 'return'
2119 if (P.enableCheckFallThrough) {
2120 const CheckFallThroughDiagnostics &CD =
2122 ? CheckFallThroughDiagnostics::MakeForBlock()
2123 : (isa<CXXMethodDecl>(D) &&
2124 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2125 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2126 ? CheckFallThroughDiagnostics::MakeForLambda()
2127 : (fscope->isCoroutine()
2128 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2129 : CheckFallThroughDiagnostics::MakeForFunction(D)));
2130 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
2133 // Warning: check for unreachable code
2134 if (P.enableCheckUnreachable) {
2135 // Only check for unreachable code on non-template instantiations.
2136 // Different template instantiations can effectively change the control-flow
2137 // and it is very difficult to prove that a snippet of code in a template
2138 // is unreachable for all instantiations.
2139 bool isTemplateInstantiation = false;
2140 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2141 isTemplateInstantiation = Function->isTemplateInstantiation();
2142 if (!isTemplateInstantiation)
2143 CheckUnreachable(S, AC);
2146 // Check for thread safety violations
2147 if (P.enableThreadSafetyAnalysis) {
2148 SourceLocation FL = AC.getDecl()->getLocation();
2149 SourceLocation FEL = AC.getDecl()->getEndLoc();
2150 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2151 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
2152 Reporter.setIssueBetaWarnings(true);
2153 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
2154 Reporter.setVerbose(true);
2156 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2157 &S.ThreadSafetyDeclCache);
2158 Reporter.emitDiagnostics();
2161 // Check for violations of consumed properties.
2162 if (P.enableConsumedAnalysis) {
2163 consumed::ConsumedWarningsHandler WarningHandler(S);
2164 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2168 if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
2169 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
2170 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())) {
2171 if (CFG *cfg = AC.getCFG()) {
2172 UninitValsDiagReporter reporter(S);
2173 UninitVariablesAnalysisStats stats;
2174 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2175 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2178 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2179 ++NumUninitAnalysisFunctions;
2180 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2181 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2182 MaxUninitAnalysisVariablesPerFunction =
2183 std::max(MaxUninitAnalysisVariablesPerFunction,
2184 stats.NumVariablesAnalyzed);
2185 MaxUninitAnalysisBlockVisitsPerFunction =
2186 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2187 stats.NumBlockVisits);
2192 bool FallThroughDiagFull =
2193 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
2194 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2195 diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
2196 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2197 fscope->HasFallthroughStmt) {
2198 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2201 if (S.getLangOpts().ObjCWeak &&
2202 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
2203 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2206 // Check for infinite self-recursion in functions
2207 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2208 D->getBeginLoc())) {
2209 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2210 checkRecursiveFunction(S, FD, Body, AC);
2214 // Check for throw out of non-throwing function.
2215 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
2216 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2217 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2218 checkThrowInNonThrowingFunc(S, FD, AC);
2220 // If none of the previous checks caused a CFG build, trigger one here
2221 // for -Wtautological-overlap-compare
2222 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2223 D->getBeginLoc())) {
2227 // Collect statistics about the CFG if it was built.
2228 if (S.CollectStats && AC.isCFGBuilt()) {
2229 ++NumFunctionsAnalyzed;
2230 if (CFG *cfg = AC.getCFG()) {
2231 // If we successfully built a CFG for this context, record some more
2232 // detail information about it.
2233 NumCFGBlocks += cfg->getNumBlockIDs();
2234 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2235 cfg->getNumBlockIDs());
2237 ++NumFunctionsWithBadCFGs;
2242 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2243 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2245 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2246 unsigned AvgCFGBlocksPerFunction =
2247 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2248 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2249 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2250 << " " << NumCFGBlocks << " CFG blocks built.\n"
2251 << " " << AvgCFGBlocksPerFunction
2252 << " average CFG blocks per function.\n"
2253 << " " << MaxCFGBlocksPerFunction
2254 << " max CFG blocks per function.\n";
2256 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2257 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2258 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2259 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2260 llvm::errs() << NumUninitAnalysisFunctions
2261 << " functions analyzed for uninitialiazed variables\n"
2262 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2263 << " " << AvgUninitVariablesPerFunction
2264 << " average variables per function.\n"
2265 << " " << MaxUninitAnalysisVariablesPerFunction
2266 << " max variables per function.\n"
2267 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2268 << " " << AvgUninitBlockVisitsPerFunction
2269 << " average block visits per function.\n"
2270 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2271 << " max block visits per function.\n";