blob: 3b73568938337812852ef8be011b2bdcc870bc59 [file] [log] [blame]
Ted Kremenek918fe842010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ted Kremenek918fe842010-03-20 21:06:02 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines analysis_warnings::[Policy,Executor].
10// Together they are used by Sema to issue warnings based on inexpensive
11// static analysis algorithms in libAnalysis.
12//
13//===----------------------------------------------------------------------===//
14
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall28a0cf72010-08-25 07:42:41 +000016#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +000018#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
Jordan Rose76831c62012-10-11 16:10:19 +000021#include "clang/AST/ParentMap.h"
Richard Smith84837d52012-05-03 18:27:39 +000022#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
DeLesley Hutchins48a31762013-08-12 21:20:55 +000027#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Analysis/Analyses/ReachableCode.h"
29#include "clang/Analysis/Analyses/ThreadSafety.h"
30#include "clang/Analysis/Analyses/UninitializedValues.h"
George Karpenkov50657f62017-09-06 21:45:03 +000031#include "clang/Analysis/AnalysisDeclContext.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000032#include "clang/Analysis/CFG.h"
Ted Kremenek3427fac2011-02-23 01:52:04 +000033#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Basic/SourceLocation.h"
35#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Lex/Preprocessor.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaInternal.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000039#include "llvm/ADT/BitVector.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000040#include "llvm/ADT/MapVector.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000041#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000042#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000043#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000044#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000045#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000046#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000047#include <iterator>
Ted Kremenek918fe842010-03-20 21:06:02 +000048
49using namespace clang;
50
51//===----------------------------------------------------------------------===//
52// Unreachable code analysis.
53//===----------------------------------------------------------------------===//
54
55namespace {
56 class UnreachableCodeHandler : public reachable_code::Callback {
57 Sema &S;
Alex Lorenz569ad732017-01-12 10:48:03 +000058 SourceRange PreviousSilenceableCondVal;
59
Ted Kremenek918fe842010-03-20 21:06:02 +000060 public:
61 UnreachableCodeHandler(Sema &s) : S(s) {}
62
Ted Kremenek1a8641c2014-03-15 01:26:32 +000063 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000064 SourceLocation L,
65 SourceRange SilenceableCondVal,
66 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000067 SourceRange R2) override {
Alex Lorenz569ad732017-01-12 10:48:03 +000068 // Avoid reporting multiple unreachable code diagnostics that are
69 // triggered by the same conditional value.
70 if (PreviousSilenceableCondVal.isValid() &&
71 SilenceableCondVal.isValid() &&
72 PreviousSilenceableCondVal == SilenceableCondVal)
73 return;
74 PreviousSilenceableCondVal = SilenceableCondVal;
75
Ted Kremenek1a8641c2014-03-15 01:26:32 +000076 unsigned diag = diag::warn_unreachable;
77 switch (UK) {
78 case reachable_code::UK_Break:
79 diag = diag::warn_unreachable_break;
80 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000081 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000082 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000083 break;
Ted Kremenek14210372014-03-21 06:02:36 +000084 case reachable_code::UK_Loop_Increment:
85 diag = diag::warn_unreachable_loop_increment;
86 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000087 case reachable_code::UK_Other:
88 break;
89 }
90
91 S.Diag(L, diag) << R1 << R2;
Fangrui Song6907ce22018-07-30 19:24:48 +000092
Ted Kremenekec3bbf42014-03-29 00:35:20 +000093 SourceLocation Open = SilenceableCondVal.getBegin();
94 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000095 SourceLocation Close = SilenceableCondVal.getEnd();
96 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000097 if (Close.isValid()) {
98 S.Diag(Open, diag::note_unreachable_silence)
99 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
100 << FixItHint::CreateInsertion(Close, ")");
101 }
102 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000103 }
104 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000105} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +0000106
107/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000108static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000109 // As a heuristic prune all diagnostics not in the main file. Currently
110 // the majority of warnings in headers are false positives. These
111 // are largely caused by configuration state, e.g. preprocessor
112 // defined code, etc.
113 //
114 // Note that this is also a performance optimization. Analyzing
115 // headers many times can be expensive.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000116 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
Ted Kremenekc1b28752014-02-25 22:35:37 +0000117 return;
118
Ted Kremenek918fe842010-03-20 21:06:02 +0000119 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000120 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000121}
122
Benjamin Kramer3a002252015-02-16 16:53:12 +0000123namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000124/// Warn on logical operator errors in CFGBuilder
Richard Trieuf935b562014-04-05 05:17:01 +0000125class LogicalErrorHandler : public CFGCallback {
126 Sema &S;
127
128public:
129 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
130
131 static bool HasMacroID(const Expr *E) {
132 if (E->getExprLoc().isMacroID())
133 return true;
134
135 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000136 for (const Stmt *SubStmt : E->children())
137 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
138 if (HasMacroID(SubExpr))
139 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000140
141 return false;
142 }
143
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000144 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000145 if (HasMacroID(B))
146 return;
147
148 SourceRange DiagRange = B->getSourceRange();
149 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
150 << DiagRange << isAlwaysTrue;
151 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000152
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000153 void compareBitwiseEquality(const BinaryOperator *B,
154 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000155 if (HasMacroID(B))
156 return;
157
158 SourceRange DiagRange = B->getSourceRange();
159 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
160 << DiagRange << isAlwaysTrue;
161 }
Richard Trieu8b0d14a2019-10-19 00:57:23 +0000162
163 void compareBitwiseOr(const BinaryOperator *B) override {
164 if (HasMacroID(B))
165 return;
166
167 SourceRange DiagRange = B->getSourceRange();
168 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_or) << DiagRange;
169 }
170
171 static bool hasActiveDiagnostics(DiagnosticsEngine &Diags,
172 SourceLocation Loc) {
173 return !Diags.isIgnored(diag::warn_tautological_overlap_comparison, Loc) ||
174 !Diags.isIgnored(diag::warn_comparison_bitwise_or, Loc);
175 }
Richard Trieuf935b562014-04-05 05:17:01 +0000176};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000177} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000178
Ted Kremenek918fe842010-03-20 21:06:02 +0000179//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000180// Check for infinite self-recursion in functions
181//===----------------------------------------------------------------------===//
182
Richard Trieu6995de92015-08-21 03:43:09 +0000183// Returns true if the function is called anywhere within the CFGBlock.
184// For member functions, the additional condition of being call from the
185// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000186static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000187 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000188 for (const auto &B : Block) {
189 if (B.getKind() != CFGElement::Statement)
190 continue;
191
192 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
193 if (!CE || !CE->getCalleeDecl() ||
194 CE->getCalleeDecl()->getCanonicalDecl() != FD)
195 continue;
196
197 // Skip function calls which are qualified with a templated class.
198 if (const DeclRefExpr *DRE =
199 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
200 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
201 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
202 isa<TemplateSpecializationType>(NNS->getAsType())) {
203 continue;
204 }
205 }
206 }
207
208 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
209 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
210 !MCE->getMethodDecl()->isVirtual())
211 return true;
212 }
213 return false;
214}
215
Robert Widmann97608442018-03-22 03:16:23 +0000216// Returns true if every path from the entry block passes through a call to FD.
Richard Trieu6995de92015-08-21 03:43:09 +0000217static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
Robert Widmann97608442018-03-22 03:16:23 +0000218 llvm::SmallPtrSet<CFGBlock *, 16> Visited;
219 llvm::SmallVector<CFGBlock *, 16> WorkList;
220 // Keep track of whether we found at least one recursive path.
221 bool foundRecursion = false;
Richard Trieu6995de92015-08-21 03:43:09 +0000222
223 const unsigned ExitID = cfg->getExit().getBlockID();
224
Robert Widmann97608442018-03-22 03:16:23 +0000225 // Seed the work list with the entry block.
226 WorkList.push_back(&cfg->getEntry());
Richard Trieu6995de92015-08-21 03:43:09 +0000227
Robert Widmann97608442018-03-22 03:16:23 +0000228 while (!WorkList.empty()) {
229 CFGBlock *Block = WorkList.pop_back_val();
Richard Trieu2f024f42013-12-21 02:33:43 +0000230
Robert Widmann97608442018-03-22 03:16:23 +0000231 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
232 if (CFGBlock *SuccBlock = *I) {
233 if (!Visited.insert(SuccBlock).second)
234 continue;
Richard Trieu2f024f42013-12-21 02:33:43 +0000235
Robert Widmann97608442018-03-22 03:16:23 +0000236 // Found a path to the exit node without a recursive call.
237 if (ExitID == SuccBlock->getBlockID())
238 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000239
Robert Widmann97608442018-03-22 03:16:23 +0000240 // If the successor block contains a recursive call, end analysis there.
241 if (hasRecursiveCallInPath(FD, *SuccBlock)) {
242 foundRecursion = true;
243 continue;
Richard Trieu6995de92015-08-21 03:43:09 +0000244 }
Richard Trieu6995de92015-08-21 03:43:09 +0000245
Robert Widmann97608442018-03-22 03:16:23 +0000246 WorkList.push_back(SuccBlock);
247 }
248 }
249 }
250 return foundRecursion;
Richard Trieu2f024f42013-12-21 02:33:43 +0000251}
252
253static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000254 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000255 FD = FD->getCanonicalDecl();
256
257 // Only run on non-templated functions and non-templated members of
258 // templated classes.
259 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
260 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
261 return;
262
263 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000264 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000265
Robert Widmann04306d622019-02-13 22:22:23 +0000266 // If the exit block is unreachable, skip processing the function.
267 if (cfg->getExit().pred_empty())
268 return;
269
Richard Trieu6995de92015-08-21 03:43:09 +0000270 // Emit diagnostic if a recursive function call is detected for all paths.
271 if (checkForRecursiveFunctionCall(FD, cfg))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000272 S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
Richard Trieu2f024f42013-12-21 02:33:43 +0000273}
274
275//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000276// Check for throw in a non-throwing function.
277//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000278
Richard Smith08482102018-02-20 02:32:30 +0000279/// Determine whether an exception thrown by E, unwinding from ThrowBlock,
280/// can reach ExitBlock.
281static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
282 CFG *Body) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000283 SmallVector<CFGBlock *, 16> Stack;
Richard Smith08482102018-02-20 02:32:30 +0000284 llvm::BitVector Queued(Body->getNumBlockIDs());
Erich Keane89fe9c22017-06-23 20:22:19 +0000285
Richard Smith08482102018-02-20 02:32:30 +0000286 Stack.push_back(&ThrowBlock);
287 Queued[ThrowBlock.getBlockID()] = true;
288
289 while (!Stack.empty()) {
290 CFGBlock &UnwindBlock = *Stack.back();
291 Stack.pop_back();
292
293 for (auto &Succ : UnwindBlock.succs()) {
294 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
Erich Keane89fe9c22017-06-23 20:22:19 +0000295 continue;
296
Richard Smith08482102018-02-20 02:32:30 +0000297 if (Succ->getBlockID() == Body->getExit().getBlockID())
298 return true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000299
Richard Smith08482102018-02-20 02:32:30 +0000300 if (auto *Catch =
301 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
302 QualType Caught = Catch->getCaughtType();
303 if (Caught.isNull() || // catch (...) catches everything
304 !E->getSubExpr() || // throw; is considered cuaght by any handler
305 S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
306 // Exception doesn't escape via this path.
307 break;
308 } else {
309 Stack.push_back(Succ);
310 Queued[Succ->getBlockID()] = true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000311 }
Richard Smith08482102018-02-20 02:32:30 +0000312 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000313 }
Richard Smith08482102018-02-20 02:32:30 +0000314
315 return false;
316}
317
318static void visitReachableThrows(
319 CFG *BodyCFG,
320 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
321 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
322 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
323 for (CFGBlock *B : *BodyCFG) {
324 if (!Reachable[B->getBlockID()])
325 continue;
326 for (CFGElement &E : *B) {
327 Optional<CFGStmt> S = E.getAs<CFGStmt>();
328 if (!S)
329 continue;
330 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
331 Visit(Throw, *B);
332 }
333 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000334}
335
336static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
337 const FunctionDecl *FD) {
Erich Keane7538b352017-07-05 16:43:45 +0000338 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
339 FD->getTypeSourceInfo()) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000340 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
341 if (S.getLangOpts().CPlusPlus11 &&
342 (isa<CXXDestructorDecl>(FD) ||
343 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
Erich Keane7538b352017-07-05 16:43:45 +0000344 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
345 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
346 getAs<FunctionProtoType>())
347 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
348 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
349 << FD->getExceptionSpecSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +0000350 } else
Erich Keane7538b352017-07-05 16:43:45 +0000351 S.Diag(FD->getLocation(), diag::note_throw_in_function)
352 << FD->getExceptionSpecSourceRange();
Erich Keane89fe9c22017-06-23 20:22:19 +0000353 }
354}
355
356static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
357 AnalysisDeclContext &AC) {
358 CFG *BodyCFG = AC.getCFG();
359 if (!BodyCFG)
360 return;
361 if (BodyCFG->getExit().pred_empty())
362 return;
Richard Smith08482102018-02-20 02:32:30 +0000363 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
364 if (throwEscapes(S, Throw, Block, BodyCFG))
365 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
366 });
Erich Keane89fe9c22017-06-23 20:22:19 +0000367}
368
369static bool isNoexcept(const FunctionDecl *FD) {
370 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000371 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
Erich Keane89fe9c22017-06-23 20:22:19 +0000372 return true;
373 return false;
374}
375
376//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000377// Check for missing return value.
378//===----------------------------------------------------------------------===//
379
John McCall5c6ec8c2010-05-16 09:34:11 +0000380enum ControlFlowKind {
381 UnknownFallThrough,
382 NeverFallThrough,
383 MaybeFallThrough,
384 AlwaysFallThrough,
385 NeverFallThroughOrReturn
386};
Ted Kremenek918fe842010-03-20 21:06:02 +0000387
388/// CheckFallThrough - Check that we don't fall off the end of a
389/// Statement that should return a value.
390///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000391/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
392/// MaybeFallThrough iff we might or might not fall off the end,
393/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
394/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000395/// statement but we may return. We assume that functions not marked noreturn
396/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000397static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000398 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000399 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000400
401 // The CFG leaves in dead things, and we don't want the dead code paths to
402 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000403 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000404 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000405 live);
406
407 bool AddEHEdges = AC.getAddEHEdges();
408 if (!AddEHEdges && count != cfg->getNumBlockIDs())
409 // When there are things remaining dead, and we didn't add EH edges
410 // from CallExprs to the catch clauses, we have to go back and
411 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000412 for (const auto *B : *cfg) {
413 if (!live[B->getBlockID()]) {
414 if (B->pred_begin() == B->pred_end()) {
Artem Dergachev4e530322019-05-24 01:34:22 +0000415 const Stmt *Term = B->getTerminatorStmt();
416 if (Term && isa<CXXTryStmt>(Term))
Ted Kremenek918fe842010-03-20 21:06:02 +0000417 // When not adding EH edges from calls, catch clauses
418 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000419 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000420 continue;
421 }
422 }
423 }
424
425 // Now we know what is live, we check the live precessors of the exit block
426 // and look for fall through paths, being careful to ignore normal returns,
427 // and exceptional paths.
428 bool HasLiveReturn = false;
429 bool HasFakeEdge = false;
430 bool HasPlainEdge = false;
431 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000432
433 // Ignore default cases that aren't likely to be reachable because all
434 // enums in a switch(X) have explicit case statements.
435 CFGBlock::FilterOptions FO;
436 FO.IgnoreDefaultsWithCoveredEnums = 1;
437
Fangrui Song99337e22018-07-20 08:19:20 +0000438 for (CFGBlock::filtered_pred_iterator I =
439 cfg->getExit().filtered_pred_start_end(FO);
440 I.hasMore(); ++I) {
441 const CFGBlock &B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000442 if (!live[B.getBlockID()])
443 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000444
Chandler Carruth03faf782011-09-13 09:53:58 +0000445 // Skip blocks which contain an element marked as no-return. They don't
446 // represent actually viable edges into the exit block, so mark them as
447 // abnormal.
448 if (B.hasNoReturnElement()) {
449 HasAbnormalEdge = true;
450 continue;
451 }
452
Ted Kremenek5d068492011-01-26 04:49:52 +0000453 // Destructors can appear after the 'return' in the CFG. This is
454 // normal. We need to look pass the destructors for the return
455 // statement (if it exists).
456 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000457
Chandler Carruth03faf782011-09-13 09:53:58 +0000458 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000459 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000460 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000461
Ted Kremenek5d068492011-01-26 04:49:52 +0000462 // No more CFGElements in the block?
463 if (ri == re) {
Artem Dergachev4e530322019-05-24 01:34:22 +0000464 const Stmt *Term = B.getTerminatorStmt();
465 if (Term && isa<CXXTryStmt>(Term)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000466 HasAbnormalEdge = true;
467 continue;
468 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000469 // A labeled empty statement, or the entry block...
470 HasPlainEdge = true;
471 continue;
472 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000473
David Blaikie2a01f5d2013-02-21 20:58:29 +0000474 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000475 const Stmt *S = CS.getStmt();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000476 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000477 HasLiveReturn = true;
478 continue;
479 }
480 if (isa<ObjCAtThrowStmt>(S)) {
481 HasFakeEdge = true;
482 continue;
483 }
484 if (isa<CXXThrowExpr>(S)) {
485 HasFakeEdge = true;
486 continue;
487 }
Chad Rosier32503022012-06-11 20:47:18 +0000488 if (isa<MSAsmStmt>(S)) {
489 // TODO: Verify this is correct.
490 HasFakeEdge = true;
491 HasLiveReturn = true;
492 continue;
493 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000494 if (isa<CXXTryStmt>(S)) {
495 HasAbnormalEdge = true;
496 continue;
497 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000498 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
499 == B.succ_end()) {
500 HasAbnormalEdge = true;
501 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000502 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000503
504 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000505 }
506 if (!HasPlainEdge) {
507 if (HasLiveReturn)
508 return NeverFallThrough;
509 return NeverFallThroughOrReturn;
510 }
511 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
512 return MaybeFallThrough;
513 // This says AlwaysFallThrough for calls to functions that are not marked
514 // noreturn, that don't return. If people would like this warning to be more
515 // accurate, such functions should be marked as noreturn.
516 return AlwaysFallThrough;
517}
518
Dan Gohman28ade552010-07-26 21:25:24 +0000519namespace {
520
Ted Kremenek918fe842010-03-20 21:06:02 +0000521struct CheckFallThroughDiagnostics {
522 unsigned diag_MaybeFallThrough_HasNoReturn;
523 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
524 unsigned diag_AlwaysFallThrough_HasNoReturn;
525 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
526 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000527 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000528 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000529
Douglas Gregor24f27692010-04-16 23:28:44 +0000530 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000531 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000532 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000533 D.diag_MaybeFallThrough_HasNoReturn =
534 diag::warn_falloff_noreturn_function;
535 D.diag_MaybeFallThrough_ReturnsNonVoid =
536 diag::warn_maybe_falloff_nonvoid_function;
537 D.diag_AlwaysFallThrough_HasNoReturn =
538 diag::warn_falloff_noreturn_function;
539 D.diag_AlwaysFallThrough_ReturnsNonVoid =
540 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000541
542 // Don't suggest that virtual functions be marked "noreturn", since they
543 // might be overridden by non-noreturn functions.
544 bool isVirtualMethod = false;
545 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
546 isVirtualMethod = Method->isVirtual();
Fangrui Song6907ce22018-07-30 19:24:48 +0000547
Douglas Gregor0de57202011-10-10 18:15:57 +0000548 // Don't suggest that template instantiations be marked "noreturn"
549 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000550 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
551 isTemplateInstantiation = Function->isTemplateInstantiation();
Fangrui Song6907ce22018-07-30 19:24:48 +0000552
Douglas Gregor0de57202011-10-10 18:15:57 +0000553 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000554 D.diag_NeverFallThroughOrReturn =
555 diag::warn_suggest_noreturn_function;
556 else
557 D.diag_NeverFallThroughOrReturn = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +0000558
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000559 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000560 return D;
561 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000562
Eric Fiselier709d1b32016-10-27 07:30:31 +0000563 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
564 CheckFallThroughDiagnostics D;
565 D.FuncLoc = Func->getLocation();
566 D.diag_MaybeFallThrough_HasNoReturn = 0;
567 D.diag_MaybeFallThrough_ReturnsNonVoid =
568 diag::warn_maybe_falloff_nonvoid_coroutine;
569 D.diag_AlwaysFallThrough_HasNoReturn = 0;
570 D.diag_AlwaysFallThrough_ReturnsNonVoid =
571 diag::warn_falloff_nonvoid_coroutine;
572 D.funMode = Coroutine;
573 return D;
574 }
575
Ted Kremenek918fe842010-03-20 21:06:02 +0000576 static CheckFallThroughDiagnostics MakeForBlock() {
577 CheckFallThroughDiagnostics D;
578 D.diag_MaybeFallThrough_HasNoReturn =
579 diag::err_noreturn_block_has_return_expr;
580 D.diag_MaybeFallThrough_ReturnsNonVoid =
581 diag::err_maybe_falloff_nonvoid_block;
582 D.diag_AlwaysFallThrough_HasNoReturn =
583 diag::err_noreturn_block_has_return_expr;
584 D.diag_AlwaysFallThrough_ReturnsNonVoid =
585 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000586 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000587 D.funMode = Block;
588 return D;
589 }
590
591 static CheckFallThroughDiagnostics MakeForLambda() {
592 CheckFallThroughDiagnostics D;
593 D.diag_MaybeFallThrough_HasNoReturn =
594 diag::err_noreturn_lambda_has_return_expr;
595 D.diag_MaybeFallThrough_ReturnsNonVoid =
596 diag::warn_maybe_falloff_nonvoid_lambda;
597 D.diag_AlwaysFallThrough_HasNoReturn =
598 diag::err_noreturn_lambda_has_return_expr;
599 D.diag_AlwaysFallThrough_ReturnsNonVoid =
600 diag::warn_falloff_nonvoid_lambda;
601 D.diag_NeverFallThroughOrReturn = 0;
602 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000603 return D;
604 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000605
David Blaikie9c902b52011-09-25 23:23:43 +0000606 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000607 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000608 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000609 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000610 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
611 FuncLoc)) &&
612 (!HasNoReturn ||
613 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
614 FuncLoc)) &&
615 (!ReturnsVoid ||
616 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000617 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000618 if (funMode == Coroutine) {
619 return (ReturnsVoid ||
620 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
621 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
622 FuncLoc)) &&
623 (!HasNoReturn);
624 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000625 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000626 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000627 }
628};
629
Hans Wennborgdcfba332015-10-06 23:40:43 +0000630} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000631
Reid Kleckner87a31802018-03-12 21:43:02 +0000632/// CheckFallThroughForBody - Check that we don't fall off the end of a
Ted Kremenek918fe842010-03-20 21:06:02 +0000633/// function that should return a value. Check that we don't fall off the end
634/// of a noreturn function. We assume that functions and blocks not marked
635/// noreturn will return.
636static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Richard Smith2fdd95c2019-05-31 00:45:09 +0000637 QualType BlockType,
Reid Kleckner87a31802018-03-12 21:43:02 +0000638 const CheckFallThroughDiagnostics &CD,
639 AnalysisDeclContext &AC,
640 sema::FunctionScopeInfo *FSI) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000641
642 bool ReturnsVoid = false;
643 bool HasNoReturn = false;
Reid Kleckner87a31802018-03-12 21:43:02 +0000644 bool IsCoroutine = FSI->isCoroutine();
Ted Kremenek918fe842010-03-20 21:06:02 +0000645
Eric Fiselier709d1b32016-10-27 07:30:31 +0000646 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
647 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
648 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
649 else
650 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000651 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000652 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000653 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000654 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000655 HasNoReturn = MD->hasAttr<NoReturnAttr>();
656 }
657 else if (isa<BlockDecl>(D)) {
Ted Kremenek0b405322010-03-23 00:13:23 +0000658 if (const FunctionType *FT =
Richard Smith2fdd95c2019-05-31 00:45:09 +0000659 BlockType->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000660 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000661 ReturnsVoid = true;
662 if (FT->getNoReturnAttr())
663 HasNoReturn = true;
664 }
665 }
666
David Blaikie9c902b52011-09-25 23:23:43 +0000667 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000668
669 // Short circuit for compilation speed.
670 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
671 return;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000672 SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000673 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
674 if (IsCoroutine)
Reid Kleckner87a31802018-03-12 21:43:02 +0000675 S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000676 else
677 S.Diag(Loc, DiagID);
678 };
Erich Keane3efe0022018-07-20 14:13:28 +0000679
680 // cpu_dispatch functions permit empty function bodies for ICC compatibility.
681 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
682 return;
683
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000684 // Either in a function body compound statement, or a function-try-block.
685 switch (CheckFallThrough(AC)) {
686 case UnknownFallThrough:
687 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000688
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000689 case MaybeFallThrough:
690 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000691 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000692 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000693 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000694 break;
695 case AlwaysFallThrough:
696 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000697 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000698 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000699 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000700 break;
701 case NeverFallThroughOrReturn:
702 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
703 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
704 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
705 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
706 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
707 } else {
708 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000709 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000710 }
711 break;
712 case NeverFallThrough:
713 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000714 }
715}
716
717//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000718// -Wuninitialized
719//===----------------------------------------------------------------------===//
720
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000721namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000722/// ContainsReference - A visitor class to search for references to
723/// a particular declaration (the needle) within any evaluated component of an
724/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000725class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000726 bool FoundReference;
727 const DeclRefExpr *Needle;
728
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000729public:
Scott Douglass503fc392015-06-10 13:53:15 +0000730 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000731
Scott Douglass503fc392015-06-10 13:53:15 +0000732 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
733 : Inherited(Context), FoundReference(false), Needle(Needle) {}
734
735 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000736 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000737 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000738 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000739
Scott Douglass503fc392015-06-10 13:53:15 +0000740 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000741 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000742
Scott Douglass503fc392015-06-10 13:53:15 +0000743 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000744 if (E == Needle)
745 FoundReference = true;
746 else
Scott Douglass503fc392015-06-10 13:53:15 +0000747 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000748 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000749
750 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000751};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000752} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000753
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000754static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000755 QualType VariableTy = VD->getType().getCanonicalType();
756 if (VariableTy->isBlockPointerType() &&
757 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000758 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
759 << VD->getDeclName()
760 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000761 return true;
762 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000763
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000764 // Don't issue a fixit if there is already an initializer.
765 if (VD->getInit())
766 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000767
768 // Don't suggest a fixit inside macros.
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000769 if (VD->getEndLoc().isMacroID())
Richard Trieu2cdcf822012-05-03 01:09:59 +0000770 return false;
771
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000772 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000773
774 // Suggest possible initialization (if any).
775 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
776 if (Init.empty())
777 return false;
778
Richard Smith8d06f422012-01-12 23:53:29 +0000779 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
780 << FixItHint::CreateInsertion(Loc, Init);
781 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000782}
783
Richard Smith1bb8edb82012-05-26 06:20:46 +0000784/// Create a fixit to remove an if-like statement, on the assumption that its
785/// condition is CondVal.
786static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
787 const Stmt *Else, bool CondVal,
788 FixItHint &Fixit1, FixItHint &Fixit2) {
789 if (CondVal) {
790 // If condition is always true, remove all but the 'then'.
791 Fixit1 = FixItHint::CreateRemoval(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000792 CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000793 if (Else) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000794 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
795 Fixit2 =
796 FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000797 }
798 } else {
799 // If condition is always false, remove all but the 'else'.
800 if (Else)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000801 Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
802 If->getBeginLoc(), Else->getBeginLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000803 else
804 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
805 }
806}
807
808/// DiagUninitUse -- Helper function to produce a diagnostic for an
809/// uninitialized use of a variable.
810static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
811 bool IsCapturedByBlock) {
812 bool Diagnosed = false;
813
Richard Smithba8071e2013-09-12 18:49:10 +0000814 switch (Use.getKind()) {
815 case UninitUse::Always:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000816 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
Richard Smithba8071e2013-09-12 18:49:10 +0000817 << VD->getDeclName() << IsCapturedByBlock
818 << Use.getUser()->getSourceRange();
819 return;
820
821 case UninitUse::AfterDecl:
822 case UninitUse::AfterCall:
823 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
824 << VD->getDeclName() << IsCapturedByBlock
825 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
826 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
827 << VD->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000828 S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
829 << IsCapturedByBlock << Use.getUser()->getSourceRange();
Richard Smithba8071e2013-09-12 18:49:10 +0000830 return;
831
832 case UninitUse::Maybe:
833 case UninitUse::Sometimes:
834 // Carry on to report sometimes-uninitialized branches, if possible,
835 // or a 'may be used uninitialized' diagnostic otherwise.
836 break;
837 }
838
Richard Smith1bb8edb82012-05-26 06:20:46 +0000839 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000840 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
841 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000842 assert(Use.getKind() == UninitUse::Sometimes);
843
844 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000845 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000846
847 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000848 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000849 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000850 SourceRange Range;
851
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000852 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000853 // For all binary terminators, branch 0 is taken if the condition is true,
854 // and branch 1 is taken if the condition is false.
855 int RemoveDiagKind = -1;
856 const char *FixitStr =
857 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
858 : (I->Output ? "1" : "0");
859 FixItHint Fixit1, Fixit2;
860
Richard Smithba8071e2013-09-12 18:49:10 +0000861 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000862 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000863 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000864 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000865 continue;
866
867 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000868 case Stmt::IfStmtClass: {
869 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000870 DiagKind = 0;
871 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000872 Range = IS->getCond()->getSourceRange();
873 RemoveDiagKind = 0;
874 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
875 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000876 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000877 }
878 case Stmt::ConditionalOperatorClass: {
879 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000880 DiagKind = 0;
881 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000882 Range = CO->getCond()->getSourceRange();
883 RemoveDiagKind = 0;
884 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
885 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000886 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000887 }
Richard Smith4323bf82012-05-25 02:17:09 +0000888 case Stmt::BinaryOperatorClass: {
889 const BinaryOperator *BO = cast<BinaryOperator>(Term);
890 if (!BO->isLogicalOp())
891 continue;
892 DiagKind = 0;
893 Str = BO->getOpcodeStr();
894 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000895 RemoveDiagKind = 0;
896 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
897 (BO->getOpcode() == BO_LOr && !I->Output))
898 // true && y -> y, false || y -> y.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000899 Fixit1 = FixItHint::CreateRemoval(
900 SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000901 else
902 // false && y -> false, true || y -> true.
903 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000904 break;
905 }
906
907 // "loop is entered / loop is exited".
908 case Stmt::WhileStmtClass:
909 DiagKind = 1;
910 Str = "while";
911 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000912 RemoveDiagKind = 1;
913 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000914 break;
915 case Stmt::ForStmtClass:
916 DiagKind = 1;
917 Str = "for";
918 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000919 RemoveDiagKind = 1;
920 if (I->Output)
921 Fixit1 = FixItHint::CreateRemoval(Range);
922 else
923 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000924 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000925 case Stmt::CXXForRangeStmtClass:
926 if (I->Output == 1) {
927 // The use occurs if a range-based for loop's body never executes.
928 // That may be impossible, and there's no syntactic fix for this,
929 // so treat it as a 'may be uninitialized' case.
930 continue;
931 }
932 DiagKind = 1;
933 Str = "for";
934 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
935 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000936
937 // "condition is true / loop is exited".
938 case Stmt::DoStmtClass:
939 DiagKind = 2;
940 Str = "do";
941 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000942 RemoveDiagKind = 1;
943 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000944 break;
945
946 // "switch case is taken".
947 case Stmt::CaseStmtClass:
948 DiagKind = 3;
949 Str = "case";
950 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
951 break;
952 case Stmt::DefaultStmtClass:
953 DiagKind = 3;
954 Str = "default";
955 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
956 break;
957 }
958
Richard Smith1bb8edb82012-05-26 06:20:46 +0000959 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
960 << VD->getDeclName() << IsCapturedByBlock << DiagKind
961 << Str << I->Output << Range;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000962 S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
963 << IsCapturedByBlock << User->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000964 if (RemoveDiagKind != -1)
965 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
966 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
967
968 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000969 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000970
971 if (!Diagnosed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000972 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000973 << VD->getDeclName() << IsCapturedByBlock
974 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000975}
976
Zequan Wu170b6862020-06-02 10:21:02 -0700977/// Diagnose uninitialized const reference usages.
978static bool DiagnoseUninitializedConstRefUse(Sema &S, const VarDecl *VD,
979 const UninitUse &Use) {
980 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_const_reference)
981 << VD->getDeclName() << Use.getUser()->getSourceRange();
982 return true;
983}
984
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000985/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
986/// uninitialized variable. This manages the different forms of diagnostic
987/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000988/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000989/// false.
990static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000991 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000992 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +0000993 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000994 // Inspect the initializer of the variable declaration which is
995 // being referenced prior to its initialization. We emit
996 // specialized diagnostics for self-initialization, and we
997 // specifically avoid warning about self references which take the
998 // form of:
999 //
1000 // int x = x;
1001 //
1002 // This is used to indicate to GCC that 'x' is intentionally left
1003 // uninitialized. Proven code paths which access 'x' in
1004 // an uninitialized state after this will still warn.
1005 if (const Expr *Initializer = VD->getInit()) {
1006 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1007 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +00001008
Richard Trieu43a2fc72012-05-09 21:08:22 +00001009 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +00001010 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +00001011 if (CR.doesContainReference()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001012 S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
1013 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
Richard Trieu43a2fc72012-05-09 21:08:22 +00001014 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +00001015 }
Chandler Carruth895904da2011-04-05 18:18:05 +00001016 }
Richard Trieu43a2fc72012-05-09 21:08:22 +00001017
Richard Smith1bb8edb82012-05-26 06:20:46 +00001018 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +00001019 } else {
Richard Smith4323bf82012-05-25 02:17:09 +00001020 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +00001021 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001022 S.Diag(BE->getBeginLoc(),
Richard Smith1bb8edb82012-05-26 06:20:46 +00001023 diag::warn_uninit_byref_blockvar_captured_by_block)
Akira Hatanaka53796d92019-04-23 23:52:02 +00001024 << VD->getDeclName()
1025 << VD->getType().getQualifiers().hasObjCLifetime();
Richard Smith1bb8edb82012-05-26 06:20:46 +00001026 else
1027 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +00001028 }
1029
1030 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +00001031 // the initializer of that declaration & we didn't already suggest
1032 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +00001033 if (!SuggestInitializationFixit(S, VD))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001034 S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
1035 << VD->getDeclName();
Chandler Carruth895904da2011-04-05 18:18:05 +00001036
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001037 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +00001038}
1039
Richard Smith84837d52012-05-03 18:27:39 +00001040namespace {
1041 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1042 public:
1043 FallthroughMapper(Sema &S)
1044 : FoundSwitchStatements(false),
1045 S(S) {
1046 }
1047
1048 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1049
1050 void markFallthroughVisited(const AttributedStmt *Stmt) {
1051 bool Found = FallthroughStmts.erase(Stmt);
1052 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +00001053 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +00001054 }
1055
1056 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1057
1058 const AttrStmts &getFallthroughStmts() const {
1059 return FallthroughStmts;
1060 }
1061
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001062 void fillReachableBlocks(CFG *Cfg) {
1063 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1064 std::deque<const CFGBlock *> BlockQueue;
1065
1066 ReachableBlocks.insert(&Cfg->getEntry());
1067 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001068 // Mark all case blocks reachable to avoid problems with switching on
1069 // constants, covered enums, etc.
1070 // These blocks can contain fall-through annotations, and we don't want to
1071 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +00001072 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001073 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +00001074 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001075 BlockQueue.push_back(B);
1076 }
1077
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001078 while (!BlockQueue.empty()) {
1079 const CFGBlock *P = BlockQueue.front();
1080 BlockQueue.pop_front();
1081 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1082 E = P->succ_end();
1083 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001084 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001085 BlockQueue.push_back(*I);
1086 }
1087 }
1088 }
1089
Richard Smith7532d372017-03-22 01:49:19 +00001090 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1091 bool IsTemplateInstantiation) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001092 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1093
Richard Smith84837d52012-05-03 18:27:39 +00001094 int UnannotatedCnt = 0;
1095 AnnotatedCnt = 0;
1096
Aaron Ballmane5195222014-05-15 20:50:47 +00001097 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +00001098 while (!BlockQueue.empty()) {
1099 const CFGBlock *P = BlockQueue.front();
1100 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +00001101 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +00001102
Artem Dergachev4e530322019-05-24 01:34:22 +00001103 const Stmt *Term = P->getTerminatorStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001104 if (Term && isa<SwitchStmt>(Term))
1105 continue; // Switch statement, good.
1106
1107 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1108 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1109 continue; // Previous case label has no statements, good.
1110
Alexander Kornienko09f15f32013-01-25 20:44:56 +00001111 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1112 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1113 continue; // Case label is preceded with a normal label, good.
1114
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001115 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001116 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1117 ElemEnd = P->rend();
1118 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001119 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1120 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith7532d372017-03-22 01:49:19 +00001121 // Don't issue a warning for an unreachable fallthrough
1122 // attribute in template instantiations as it may not be
1123 // unreachable in all instantiations of the template.
1124 if (!IsTemplateInstantiation)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001125 S.Diag(AS->getBeginLoc(),
Richard Smith7532d372017-03-22 01:49:19 +00001126 diag::warn_fallthrough_attr_unreachable);
Richard Smith84837d52012-05-03 18:27:39 +00001127 markFallthroughVisited(AS);
1128 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001129 break;
Richard Smith84837d52012-05-03 18:27:39 +00001130 }
1131 // Don't care about other unreachable statements.
1132 }
1133 }
1134 // If there are no unreachable statements, this may be a special
1135 // case in CFG:
1136 // case X: {
1137 // A a; // A has a destructor.
1138 // break;
1139 // }
1140 // // <<<< This place is represented by a 'hanging' CFG block.
1141 // case Y:
1142 continue;
1143 }
1144
1145 const Stmt *LastStmt = getLastStmt(*P);
1146 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1147 markFallthroughVisited(AS);
1148 ++AnnotatedCnt;
1149 continue; // Fallthrough annotation, good.
1150 }
1151
1152 if (!LastStmt) { // This block contains no executable statements.
1153 // Traverse its predecessors.
1154 std::copy(P->pred_begin(), P->pred_end(),
1155 std::back_inserter(BlockQueue));
1156 continue;
1157 }
1158
1159 ++UnannotatedCnt;
1160 }
1161 return !!UnannotatedCnt;
1162 }
1163
1164 // RecursiveASTVisitor setup.
1165 bool shouldWalkTypesOfTypeLocs() const { return false; }
1166
1167 bool VisitAttributedStmt(AttributedStmt *S) {
1168 if (asFallThroughAttr(S))
1169 FallthroughStmts.insert(S);
1170 return true;
1171 }
1172
1173 bool VisitSwitchStmt(SwitchStmt *S) {
1174 FoundSwitchStatements = true;
1175 return true;
1176 }
1177
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001178 // We don't want to traverse local type declarations. We analyze their
1179 // methods separately.
1180 bool TraverseDecl(Decl *D) { return true; }
1181
Alexander Kornienkobf911642014-06-24 15:28:21 +00001182 // We analyze lambda bodies separately. Skip them here.
Sam McCalle60151c2019-01-14 10:31:42 +00001183 bool TraverseLambdaExpr(LambdaExpr *LE) {
1184 // Traverse the captures, but not the body.
Mark de Wever3ec61282019-12-17 21:54:32 +01001185 for (const auto C : zip(LE->captures(), LE->capture_inits()))
Sam McCalle60151c2019-01-14 10:31:42 +00001186 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
1187 return true;
1188 }
Alexander Kornienkobf911642014-06-24 15:28:21 +00001189
Richard Smith84837d52012-05-03 18:27:39 +00001190 private:
1191
1192 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1193 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1194 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1195 return AS;
1196 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001197 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001198 }
1199
1200 static const Stmt *getLastStmt(const CFGBlock &B) {
Artem Dergachev4e530322019-05-24 01:34:22 +00001201 if (const Stmt *Term = B.getTerminatorStmt())
Richard Smith84837d52012-05-03 18:27:39 +00001202 return Term;
1203 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1204 ElemEnd = B.rend();
1205 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001206 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1207 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001208 }
1209 // Workaround to detect a statement thrown out by CFGBuilder:
1210 // case X: {} case Y:
1211 // case X: ; case Y:
1212 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1213 if (!isa<SwitchCase>(SW->getSubStmt()))
1214 return SW->getSubStmt();
1215
Craig Topperc3ec1492014-05-26 06:22:03 +00001216 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001217 }
1218
1219 bool FoundSwitchStatements;
1220 AttrStmts FallthroughStmts;
1221 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001222 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001223 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001224} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001225
Richard Smith4f902c72016-03-08 00:32:55 +00001226static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1227 SourceLocation Loc) {
1228 TokenValue FallthroughTokens[] = {
1229 tok::l_square, tok::l_square,
1230 PP.getIdentifierInfo("fallthrough"),
1231 tok::r_square, tok::r_square
1232 };
1233
1234 TokenValue ClangFallthroughTokens[] = {
1235 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1236 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1237 tok::r_square, tok::r_square
1238 };
1239
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +00001240 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17 && !PP.getLangOpts().C2x;
Richard Smith4f902c72016-03-08 00:32:55 +00001241
1242 StringRef MacroName;
1243 if (PreferClangAttr)
1244 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1245 if (MacroName.empty())
1246 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1247 if (MacroName.empty() && !PreferClangAttr)
1248 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +00001249 if (MacroName.empty()) {
1250 if (!PreferClangAttr)
1251 MacroName = "[[fallthrough]]";
1252 else if (PP.getLangOpts().CPlusPlus)
1253 MacroName = "[[clang::fallthrough]]";
1254 else
1255 MacroName = "__attribute__((fallthrough))";
1256 }
Richard Smith4f902c72016-03-08 00:32:55 +00001257 return MacroName;
1258}
1259
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001260static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001261 bool PerFunction) {
Richard Smith84837d52012-05-03 18:27:39 +00001262 FallthroughMapper FM(S);
1263 FM.TraverseStmt(AC.getBody());
1264
1265 if (!FM.foundSwitchStatements())
1266 return;
1267
Alexis Hunt2178f142012-06-15 21:22:05 +00001268 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001269 return;
1270
Richard Smith84837d52012-05-03 18:27:39 +00001271 CFG *Cfg = AC.getCFG();
1272
1273 if (!Cfg)
1274 return;
1275
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001276 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001277
Pete Cooper57d3f142015-07-30 17:22:52 +00001278 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001279 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001280
1281 if (!Label || !isa<SwitchCase>(Label))
1282 continue;
1283
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001284 int AnnotatedCnt;
1285
Richard Smith7532d372017-03-22 01:49:19 +00001286 bool IsTemplateInstantiation = false;
1287 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1288 IsTemplateInstantiation = Function->isTemplateInstantiation();
1289 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1290 IsTemplateInstantiation))
Richard Smith84837d52012-05-03 18:27:39 +00001291 continue;
1292
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001293 S.Diag(Label->getBeginLoc(),
1294 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1295 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001296
1297 if (!AnnotatedCnt) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001298 SourceLocation L = Label->getBeginLoc();
Richard Smith84837d52012-05-03 18:27:39 +00001299 if (L.isMacroID())
1300 continue;
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +00001301
1302 const Stmt *Term = B->getTerminatorStmt();
1303 // Skip empty cases.
1304 while (B->empty() && !Term && B->succ_size() == 1) {
1305 B = *B->succ_begin();
1306 Term = B->getTerminatorStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001307 }
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +00001308 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1309 Preprocessor &PP = S.getPreprocessor();
1310 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1311 SmallString<64> TextToInsert(AnnotationSpelling);
1312 TextToInsert += "; ";
1313 S.Diag(L, diag::note_insert_fallthrough_fixit)
1314 << AnnotationSpelling
1315 << FixItHint::CreateInsertion(L, TextToInsert);
1316 }
1317 S.Diag(L, diag::note_insert_break_fixit)
1318 << FixItHint::CreateInsertion(L, "break; ");
Richard Smith84837d52012-05-03 18:27:39 +00001319 }
1320 }
1321
Aaron Ballmane5195222014-05-15 20:50:47 +00001322 for (const auto *F : FM.getFallthroughStmts())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001323 S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001324}
1325
Jordan Rose25c0ea82012-10-29 17:46:47 +00001326static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1327 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001328 assert(S);
1329
1330 do {
1331 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001332 case Stmt::ForStmtClass:
1333 case Stmt::WhileStmtClass:
1334 case Stmt::CXXForRangeStmtClass:
1335 case Stmt::ObjCForCollectionStmtClass:
1336 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001337 case Stmt::DoStmtClass: {
Fangrui Song407659a2018-11-30 23:41:18 +00001338 Expr::EvalResult Result;
1339 if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx))
Jordan Rose25c0ea82012-10-29 17:46:47 +00001340 return true;
Fangrui Song407659a2018-11-30 23:41:18 +00001341 return Result.Val.getInt().getBoolValue();
Jordan Rose25c0ea82012-10-29 17:46:47 +00001342 }
Jordan Rose76831c62012-10-11 16:10:19 +00001343 default:
1344 break;
1345 }
1346 } while ((S = PM.getParent(S)));
1347
1348 return false;
1349}
1350
Jordan Rosed3934582012-09-28 22:21:30 +00001351static void diagnoseRepeatedUseOfWeak(Sema &S,
1352 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001353 const Decl *D,
1354 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001355 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1356 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1357 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001358 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1359 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001360
Jordan Rose25c0ea82012-10-29 17:46:47 +00001361 ASTContext &Ctx = S.getASTContext();
1362
Jordan Rosed3934582012-09-28 22:21:30 +00001363 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1364
1365 // Extract all weak objects that are referenced more than once.
1366 SmallVector<StmtUsesPair, 8> UsesByStmt;
1367 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1368 I != E; ++I) {
1369 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001370
1371 // Find the first read of the weak object.
1372 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1373 for ( ; UI != UE; ++UI) {
1374 if (UI->isUnsafe())
1375 break;
1376 }
1377
1378 // If there were only writes to this object, don't warn.
1379 if (UI == UE)
1380 continue;
1381
Jordan Rose76831c62012-10-11 16:10:19 +00001382 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001383 // read is not within a loop, don't warn. Additionally, don't warn in a
1384 // loop if the base object is a local variable -- local variables are often
1385 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001386 if (UI == Uses.begin()) {
1387 WeakUseVector::const_iterator UI2 = UI;
1388 for (++UI2; UI2 != UE; ++UI2)
1389 if (UI2->isUnsafe())
1390 break;
1391
Jordan Rose25c0ea82012-10-29 17:46:47 +00001392 if (UI2 == UE) {
1393 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001394 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001395
1396 const WeakObjectProfileTy &Profile = I->first;
1397 if (!Profile.isExactProfile())
1398 continue;
1399
1400 const NamedDecl *Base = Profile.getBase();
1401 if (!Base)
1402 Base = Profile.getProperty();
1403 assert(Base && "A profile always has a base or property.");
1404
1405 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1406 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1407 continue;
1408 }
Jordan Rose76831c62012-10-11 16:10:19 +00001409 }
1410
Jordan Rosed3934582012-09-28 22:21:30 +00001411 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1412 }
1413
1414 if (UsesByStmt.empty())
1415 return;
1416
1417 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001418 SourceManager &SM = S.getSourceManager();
Fangrui Song55fab262018-09-26 22:16:28 +00001419 llvm::sort(UsesByStmt,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001420 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001421 return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
1422 RHS.first->getBeginLoc());
1423 });
Jordan Rosed3934582012-09-28 22:21:30 +00001424
1425 // Classify the current code body for better warning text.
1426 // This enum should stay in sync with the cases in
1427 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1428 // FIXME: Should we use a common classification enum and the same set of
1429 // possibilities all throughout Sema?
1430 enum {
1431 Function,
1432 Method,
1433 Block,
1434 Lambda
1435 } FunctionKind;
1436
1437 if (isa<sema::BlockScopeInfo>(CurFn))
1438 FunctionKind = Block;
1439 else if (isa<sema::LambdaScopeInfo>(CurFn))
1440 FunctionKind = Lambda;
1441 else if (isa<ObjCMethodDecl>(D))
1442 FunctionKind = Method;
1443 else
1444 FunctionKind = Function;
1445
1446 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001447 for (const auto &P : UsesByStmt) {
1448 const Stmt *FirstRead = P.first;
1449 const WeakObjectProfileTy &Key = P.second->first;
1450 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001451
Jordan Rose657b5f42012-09-28 22:21:35 +00001452 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1453 // may not contain enough information to determine that these are different
1454 // properties. We can only be 100% sure of a repeated use in certain cases,
1455 // and we adjust the diagnostic kind accordingly so that the less certain
1456 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001457 unsigned DiagKind;
1458 if (Key.isExactProfile())
1459 DiagKind = diag::warn_arc_repeated_use_of_weak;
1460 else
1461 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1462
Jordan Rose657b5f42012-09-28 22:21:35 +00001463 // Classify the weak object being accessed for better warning text.
1464 // This enum should stay in sync with the cases in
1465 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1466 enum {
1467 Variable,
1468 Property,
1469 ImplicitProperty,
1470 Ivar
1471 } ObjectKind;
1472
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001473 const NamedDecl *KeyProp = Key.getProperty();
1474 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001475 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001476 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001477 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001478 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001479 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001480 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001481 ObjectKind = Ivar;
1482 else
1483 llvm_unreachable("Unexpected weak object kind!");
1484
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001485 // Do not warn about IBOutlet weak property receivers being set to null
1486 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001487 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001488 if (Prop->hasAttr<IBOutletAttr>())
1489 continue;
1490
Jordan Rosed3934582012-09-28 22:21:30 +00001491 // Show the first time the object was read.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001492 S.Diag(FirstRead->getBeginLoc(), DiagKind)
1493 << int(ObjectKind) << KeyProp << int(FunctionKind)
1494 << FirstRead->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001495
1496 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001497 for (const auto &Use : Uses) {
1498 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001499 continue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001500 S.Diag(Use.getUseExpr()->getBeginLoc(),
Jordan Rosed3934582012-09-28 22:21:30 +00001501 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001502 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001503 }
1504 }
1505}
1506
Jordan Rosed3934582012-09-28 22:21:30 +00001507namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001508class UninitValsDiagReporter : public UninitVariablesHandler {
1509 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001510 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001511 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001512 // Prefer using MapVector to DenseMap, so that iteration order will be
1513 // the same as insertion order. This is needed to obtain a deterministic
1514 // order of diagnostics when calling flushDiagnostics().
1515 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001516 UsesMap uses;
Zequan Wu170b6862020-06-02 10:21:02 -07001517 UsesMap constRefUses;
Fangrui Song6907ce22018-07-30 19:24:48 +00001518
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001519public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001520 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001521 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001522
Zequan Wu170b6862020-06-02 10:21:02 -07001523 MappedType &getUses(UsesMap &um, const VarDecl *vd) {
1524 MappedType &V = um[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001525 if (!V.getPointer())
1526 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001527 return V;
1528 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001529
1530 void handleUseOfUninitVariable(const VarDecl *vd,
1531 const UninitUse &use) override {
Zequan Wu170b6862020-06-02 10:21:02 -07001532 getUses(uses, vd).getPointer()->push_back(use);
1533 }
1534
1535 void handleConstRefUseOfUninitVariable(const VarDecl *vd,
1536 const UninitUse &use) override {
1537 getUses(constRefUses, vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001538 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001539
Craig Toppere14c0f82014-03-12 04:55:44 +00001540 void handleSelfInit(const VarDecl *vd) override {
Zequan Wu170b6862020-06-02 10:21:02 -07001541 getUses(uses, vd).setInt(true);
1542 getUses(constRefUses, vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001543 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001544
Ted Kremenek39fa0562011-01-21 19:41:41 +00001545 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001546 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001547 const VarDecl *vd = P.first;
1548 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001549
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001550 UsesVec *vec = V.getPointer();
1551 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001552
Fangrui Song6907ce22018-07-30 19:24:48 +00001553 // Specially handle the case where we have uses of an uninitialized
Ted Kremenek596fa162011-10-13 18:50:06 +00001554 // variable, but the root cause is an idiomatic self-init. We want
1555 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001556 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001557 DiagnoseUninitializedUse(S, vd,
1558 UninitUse(vd->getInit()->IgnoreParenCasts(),
1559 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001560 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001561 else {
1562 // Sort the uses by their SourceLocations. While not strictly
1563 // guaranteed to produce them in line/column order, this will provide
1564 // a stable ordering.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001565 llvm::sort(vec->begin(), vec->end(),
1566 [](const UninitUse &a, const UninitUse &b) {
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001567 // Prefer a more confident report over a less confident one.
1568 if (a.getKind() != b.getKind())
1569 return a.getKind() > b.getKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001570 return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001571 });
1572
Aaron Ballmane5195222014-05-15 20:50:47 +00001573 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001574 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001575 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001576
1577 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001578 // Skip further diagnostics for this variable. We try to warn only
1579 // on the first point at which a variable is used uninitialized.
1580 break;
1581 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001582 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001583
Ted Kremenek596fa162011-10-13 18:50:06 +00001584 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001585 delete vec;
1586 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001587
1588 uses.clear();
Zequan Wu170b6862020-06-02 10:21:02 -07001589
1590 // Flush all const reference uses diags.
1591 for (const auto &P : constRefUses) {
1592 const VarDecl *vd = P.first;
1593 const MappedType &V = P.second;
1594
1595 UsesVec *vec = V.getPointer();
1596 bool hasSelfInit = V.getInt();
1597
1598 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1599 DiagnoseUninitializedUse(S, vd,
1600 UninitUse(vd->getInit()->IgnoreParenCasts(),
1601 /* isAlwaysUninit */ true),
1602 /* alwaysReportSelfInit */ true);
1603 else {
1604 for (const auto &U : *vec) {
1605 if (DiagnoseUninitializedConstRefUse(S, vd, U))
1606 break;
1607 }
1608 }
1609
1610 // Release the uses vector.
1611 delete vec;
1612 }
1613
1614 constRefUses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001615 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001616
1617private:
1618 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001619 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1620 return U.getKind() == UninitUse::Always ||
1621 U.getKind() == UninitUse::AfterCall ||
1622 U.getKind() == UninitUse::AfterDecl;
1623 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001624 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001625};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001626} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001627
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001628namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001629namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001630typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001631typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001632typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001633
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001634struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001635 SourceManager &SM;
1636 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001637
1638 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1639 // Although this call will be slow, this is only called when outputting
1640 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001641 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001642 }
1643};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001644} // anonymous namespace
1645} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001646
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001647//===----------------------------------------------------------------------===//
1648// -Wthread-safety
1649//===----------------------------------------------------------------------===//
1650namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001651namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001652namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001653class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001654 Sema &S;
1655 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001656 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001657
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001658 const FunctionDecl *CurrentFunction;
1659 bool Verbose;
1660
Aaron Ballman71291bc2014-08-15 12:38:17 +00001661 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001662 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001663 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001664 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001665 << CurrentFunction);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001666 return OptionalNotes(1, FNote);
1667 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001668 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001669 }
1670
Aaron Ballman71291bc2014-08-15 12:38:17 +00001671 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001672 OptionalNotes ONS(1, Note);
1673 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001674 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001675 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001676 << CurrentFunction);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001677 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001678 }
1679 return ONS;
1680 }
1681
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001682 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1683 const PartialDiagnosticAt &Note2) const {
1684 OptionalNotes ONS;
1685 ONS.push_back(Note1);
1686 ONS.push_back(Note2);
1687 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001688 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001689 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001690 << CurrentFunction);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001691 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001692 }
1693 return ONS;
1694 }
1695
Aaron Puchertad4d52a2019-03-18 23:26:54 +00001696 OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) {
1697 return LocLocked.isValid()
1698 ? getNotes(PartialDiagnosticAt(
1699 LocLocked, S.PDiag(diag::note_locked_here) << Kind))
1700 : getNotes();
1701 }
1702
Aaron Puchertf70912f2020-06-08 16:30:06 +02001703 OptionalNotes makeUnlockedHereNote(SourceLocation LocUnlocked,
1704 StringRef Kind) {
1705 return LocUnlocked.isValid()
1706 ? getNotes(PartialDiagnosticAt(
1707 LocUnlocked, S.PDiag(diag::note_unlocked_here) << Kind))
1708 : getNotes();
1709 }
1710
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001711 public:
Richard Smith92286672012-02-03 04:45:26 +00001712 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001713 : S(S), FunLocation(FL), FunEndLocation(FEL),
1714 CurrentFunction(nullptr), Verbose(false) {}
1715
1716 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001718 /// Emit all buffered diagnostics in order of sourcelocation.
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001719 /// We need to output diagnostics produced while iterating through
1720 /// the lockset in deterministic order, so this function orders diagnostics
1721 /// and outputs them.
1722 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001723 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001724 for (const auto &Diag : Warnings) {
1725 S.Diag(Diag.first.first, Diag.first.second);
1726 for (const auto &Note : Diag.second)
1727 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001728 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001729 }
1730
Aaron Ballmane0449042014-04-01 21:43:23 +00001731 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1732 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1733 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001734 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001735 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001736
Aaron Puchertf70912f2020-06-08 16:30:06 +02001737 void handleUnmatchedUnlock(StringRef Kind, Name LockName, SourceLocation Loc,
1738 SourceLocation LocPreviousUnlock) override {
Aaron Puchertffa1d6a2019-01-29 22:11:42 +00001739 if (Loc.isInvalid())
1740 Loc = FunLocation;
1741 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_but_no_lock)
1742 << Kind << LockName);
Aaron Puchertf70912f2020-06-08 16:30:06 +02001743 Warnings.emplace_back(std::move(Warning),
1744 makeUnlockedHereNote(LocPreviousUnlock, Kind));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001745 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001746
Aaron Ballmane0449042014-04-01 21:43:23 +00001747 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1748 LockKind Expected, LockKind Received,
Aaron Puchertad4d52a2019-03-18 23:26:54 +00001749 SourceLocation LocLocked,
Aaron Puchertdc087de2019-03-19 00:14:46 +00001750 SourceLocation LocUnlock) override {
1751 if (LocUnlock.isInvalid())
1752 LocUnlock = FunLocation;
1753 PartialDiagnosticAt Warning(
1754 LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch)
1755 << Kind << LockName << Received << Expected);
Aaron Puchertad4d52a2019-03-18 23:26:54 +00001756 Warnings.emplace_back(std::move(Warning),
1757 makeLockedHereNote(LocLocked, Kind));
Aaron Ballmandf115d92014-03-21 14:48:48 +00001758 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001759
Aaron Puchertffa1d6a2019-01-29 22:11:42 +00001760 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked,
Aaron Puchertdc087de2019-03-19 00:14:46 +00001761 SourceLocation LocDoubleLock) override {
1762 if (LocDoubleLock.isInvalid())
1763 LocDoubleLock = FunLocation;
1764 PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(diag::warn_double_lock)
1765 << Kind << LockName);
Aaron Puchertad4d52a2019-03-18 23:26:54 +00001766 Warnings.emplace_back(std::move(Warning),
1767 makeLockedHereNote(LocLocked, Kind));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001768 }
1769
Aaron Ballmane0449042014-04-01 21:43:23 +00001770 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1771 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001772 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001773 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001774 unsigned DiagID = 0;
1775 switch (LEK) {
1776 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001777 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001778 break;
1779 case LEK_LockedSomeLoopIterations:
1780 DiagID = diag::warn_expecting_lock_held_on_loop;
1781 break;
1782 case LEK_LockedAtEndOfFunction:
1783 DiagID = diag::warn_no_unlock;
1784 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001785 case LEK_NotLockedAtEndOfFunction:
1786 DiagID = diag::warn_expecting_locked;
1787 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001788 }
Richard Smith92286672012-02-03 04:45:26 +00001789 if (LocEndOfScope.isInvalid())
1790 LocEndOfScope = FunEndLocation;
1791
Aaron Ballmane0449042014-04-01 21:43:23 +00001792 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1793 << LockName);
Aaron Puchertad4d52a2019-03-18 23:26:54 +00001794 Warnings.emplace_back(std::move(Warning),
1795 makeLockedHereNote(LocLocked, Kind));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001796 }
1797
Aaron Ballmane0449042014-04-01 21:43:23 +00001798 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1799 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001800 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001801 PartialDiagnosticAt Warning(Loc1,
1802 S.PDiag(diag::warn_lock_exclusive_and_shared)
1803 << Kind << LockName);
1804 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1805 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001806 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001807 }
1808
Aaron Ballmane0449042014-04-01 21:43:23 +00001809 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1810 ProtectedOperationKind POK, AccessKind AK,
1811 SourceLocation Loc) override {
1812 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1813 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001814 unsigned DiagID = POK == POK_VarAccess?
1815 diag::warn_variable_requires_any_lock:
1816 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001817 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
Richard Trieub4025802018-03-28 04:16:13 +00001818 << D << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001819 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001820 }
1821
Aaron Ballmane0449042014-04-01 21:43:23 +00001822 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1823 ProtectedOperationKind POK, Name LockName,
1824 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001825 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001826 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001827 if (PossibleMatch) {
1828 switch (POK) {
1829 case POK_VarAccess:
1830 DiagID = diag::warn_variable_requires_lock_precise;
1831 break;
1832 case POK_VarDereference:
1833 DiagID = diag::warn_var_deref_requires_lock_precise;
1834 break;
1835 case POK_FunctionCall:
1836 DiagID = diag::warn_fun_requires_lock_precise;
1837 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001838 case POK_PassByRef:
1839 DiagID = diag::warn_guarded_pass_by_reference;
1840 break;
1841 case POK_PtPassByRef:
1842 DiagID = diag::warn_pt_guarded_pass_by_reference;
1843 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001844 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001845 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
Richard Trieub4025802018-03-28 04:16:13 +00001846 << D
Aaron Ballmane0449042014-04-01 21:43:23 +00001847 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001848 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001849 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001850 if (Verbose && POK == POK_VarAccess) {
1851 PartialDiagnosticAt VNote(D->getLocation(),
1852 S.PDiag(diag::note_guarded_by_declared_here)
1853 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001854 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001855 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001856 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001857 } else {
1858 switch (POK) {
1859 case POK_VarAccess:
1860 DiagID = diag::warn_variable_requires_lock;
1861 break;
1862 case POK_VarDereference:
1863 DiagID = diag::warn_var_deref_requires_lock;
1864 break;
1865 case POK_FunctionCall:
1866 DiagID = diag::warn_fun_requires_lock;
1867 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001868 case POK_PassByRef:
1869 DiagID = diag::warn_guarded_pass_by_reference;
1870 break;
1871 case POK_PtPassByRef:
1872 DiagID = diag::warn_pt_guarded_pass_by_reference;
1873 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001874 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001875 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
Richard Trieub4025802018-03-28 04:16:13 +00001876 << D
Aaron Ballmane0449042014-04-01 21:43:23 +00001877 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001878 if (Verbose && POK == POK_VarAccess) {
1879 PartialDiagnosticAt Note(D->getLocation(),
Richard Trieub4025802018-03-28 04:16:13 +00001880 S.PDiag(diag::note_guarded_by_declared_here));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001881 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001882 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001883 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001884 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001885 }
1886
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001887 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1888 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001889 PartialDiagnosticAt Warning(Loc,
1890 S.PDiag(diag::warn_acquire_requires_negative_cap)
1891 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001892 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001893 }
1894
Aaron Ballmane0449042014-04-01 21:43:23 +00001895 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001896 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001897 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1898 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001899 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001900 }
1901
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001902 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1903 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001904 PartialDiagnosticAt Warning(Loc,
1905 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001906 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001907 }
1908
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001909 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001910 PartialDiagnosticAt Warning(Loc,
1911 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001912 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001913 }
1914
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001915 void enterFunction(const FunctionDecl* FD) override {
1916 CurrentFunction = FD;
1917 }
1918
1919 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001920 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001921 }
1922};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001923} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001924} // namespace threadSafety
1925} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001926
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001927//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001928// -Wconsumed
1929//===----------------------------------------------------------------------===//
1930
1931namespace clang {
1932namespace consumed {
1933namespace {
1934class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
Fangrui Song6907ce22018-07-30 19:24:48 +00001935
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001936 Sema &S;
1937 DiagList Warnings;
Fangrui Song6907ce22018-07-30 19:24:48 +00001938
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001939public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001940
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001941 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001942
1943 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001944 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001945 for (const auto &Diag : Warnings) {
1946 S.Diag(Diag.first.first, Diag.first.second);
1947 for (const auto &Note : Diag.second)
1948 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001949 }
1950 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001951
1952 void warnLoopStateMismatch(SourceLocation Loc,
1953 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001954 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1955 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001956
1957 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001958 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001959
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001960 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1961 StringRef VariableName,
1962 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001963 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001964
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001965 PartialDiagnosticAt Warning(Loc, S.PDiag(
1966 diag::warn_param_return_typestate_mismatch) << VariableName <<
1967 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001968
1969 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001970 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001971
DeLesley Hutchins69391772013-10-17 23:23:53 +00001972 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001973 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001974
DeLesley Hutchins69391772013-10-17 23:23:53 +00001975 PartialDiagnosticAt Warning(Loc, S.PDiag(
1976 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001977
1978 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001979 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001980
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001981 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001982 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001983 PartialDiagnosticAt Warning(Loc, S.PDiag(
1984 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001985
1986 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001987 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001988
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001989 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001990 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001991
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001992 PartialDiagnosticAt Warning(Loc, S.PDiag(
1993 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001994
1995 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001996 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001997
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001998 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001999 SourceLocation Loc) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00002000
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002001 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002002 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002003
2004 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002005 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002006
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002007 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00002008 StringRef State, SourceLocation Loc) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00002009
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002010 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
2011 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002012
2013 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002014 }
2015};
Hans Wennborgdcfba332015-10-06 23:40:43 +00002016} // anonymous namespace
2017} // namespace consumed
2018} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002019
2020//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00002021// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
2022// warnings on a function, method, or block.
2023//===----------------------------------------------------------------------===//
2024
Ted Kremenek0b405322010-03-23 00:13:23 +00002025clang::sema::AnalysisBasedWarnings::Policy::Policy() {
2026 enableCheckFallThrough = 1;
2027 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002028 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002029 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00002030}
2031
Ted Kremenekad8753c2014-03-15 05:47:06 +00002032static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002033 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00002034}
2035
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002036clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2037 : S(s),
2038 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002039 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002040 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002041 MaxCFGBlocksPerFunction(0),
2042 NumUninitAnalysisFunctions(0),
2043 NumUninitAnalysisVariables(0),
2044 MaxUninitAnalysisVariablesPerFunction(0),
2045 NumUninitAnalysisBlockVisits(0),
2046 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00002047
2048 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00002049 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00002050
2051 DefaultPolicy.enableCheckUnreachable =
2052 isEnabled(D, warn_unreachable) ||
2053 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00002054 isEnabled(D, warn_unreachable_return) ||
2055 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00002056
2057 DefaultPolicy.enableThreadSafetyAnalysis =
2058 isEnabled(D, warn_double_lock);
2059
2060 DefaultPolicy.enableConsumedAnalysis =
2061 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00002062}
2063
Aaron Ballmane5195222014-05-15 20:50:47 +00002064static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2065 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00002066 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00002067}
2068
Ted Kremenek0b405322010-03-23 00:13:23 +00002069void clang::sema::
2070AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00002071 sema::FunctionScopeInfo *fscope,
Richard Smith2fdd95c2019-05-31 00:45:09 +00002072 const Decl *D, QualType BlockType) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00002073
Ted Kremenek918fe842010-03-20 21:06:02 +00002074 // We avoid doing analysis-based warnings when there are errors for
2075 // two reasons:
2076 // (1) The CFGs often can't be constructed (if the body is invalid), so
2077 // don't bother trying.
2078 // (2) The code already has problems; running the analysis just takes more
2079 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00002080 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00002081
Olivier Goffart270ced22017-11-23 08:15:22 +00002082 // Do not do any analysis if we are going to just ignore them.
2083 if (Diags.getIgnoreAllWarnings() ||
2084 (Diags.getSuppressSystemWarnings() &&
2085 S.SourceMgr.isInSystemHeader(D->getLocation())))
Ted Kremenek0b405322010-03-23 00:13:23 +00002086 return;
2087
John McCall1d570a72010-08-25 05:56:39 +00002088 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00002089 if (cast<DeclContext>(D)->isDependentContext())
2090 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00002091
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002092 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002093 // Flush out any possibly unreachable diagnostics.
2094 flushDiagnostics(S, fscope);
2095 return;
2096 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002097
Ted Kremenek918fe842010-03-20 21:06:02 +00002098 const Stmt *Body = D->getBody();
2099 assert(Body);
2100
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002101 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00002102 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00002103
Ted Kremenek918fe842010-03-20 21:06:02 +00002104 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00002105 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00002106 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2107 AC.getCFGBuildOptions().AddEHEdges = false;
2108 AC.getCFGBuildOptions().AddInitializers = true;
2109 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002110 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00002111 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00002112 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002113
Ted Kremenek9e100ea2011-07-19 14:18:48 +00002114 // Force that certain expressions appear as CFGElements in the CFG. This
2115 // is used to speed up various analyses.
2116 // FIXME: This isn't the right factoring. This is here for initial
2117 // prototyping, but we need a way for analyses to say what expressions they
2118 // expect to always be CFGElements and then fill in the BuildOptions
2119 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002120 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2121 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002122 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00002123 AC.getCFGBuildOptions().setAllAlwaysAdd();
2124 }
2125 else {
2126 AC.getCFGBuildOptions()
2127 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00002128 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00002129 .setAlwaysAdd(Stmt::BlockExprClass)
2130 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2131 .setAlwaysAdd(Stmt::DeclRefExprClass)
2132 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00002133 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2134 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00002135 }
Ted Kremenek918fe842010-03-20 21:06:02 +00002136
Richard Trieu8b0d14a2019-10-19 00:57:23 +00002137 // Install the logical handler.
George Burgess IVb65955e2018-08-05 01:37:07 +00002138 llvm::Optional<LogicalErrorHandler> LEH;
Richard Trieu8b0d14a2019-10-19 00:57:23 +00002139 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) {
George Burgess IVb65955e2018-08-05 01:37:07 +00002140 LEH.emplace(S);
2141 AC.getCFGBuildOptions().Observer = &*LEH;
Richard Trieuf935b562014-04-05 05:17:01 +00002142 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002143
Ted Kremenek3427fac2011-02-23 01:52:04 +00002144 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00002145 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002146 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00002147
2148 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00002149 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Richard Smith7d02ca42019-05-06 04:14:01 +00002150 for (const Stmt *S : D.Stmts)
2151 AC.registerForcedBlockExpression(S);
Ted Kremeneka099c592011-03-10 03:50:34 +00002152 }
2153
2154 if (AC.getCFG()) {
2155 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00002156 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Richard Smith7d02ca42019-05-06 04:14:01 +00002157 bool AllReachable = true;
2158 for (const Stmt *S : D.Stmts) {
2159 const CFGBlock *block = AC.getBlockForRegisteredExpression(S);
Eli Friedmane0afc982012-01-21 01:01:51 +00002160 CFGReverseBlockReachabilityAnalysis *cra =
2161 AC.getCFGReachablityAnalysis();
2162 // FIXME: We should be able to assert that block is non-null, but
2163 // the CFG analysis can skip potentially-evaluated expressions in
2164 // edge cases; see test/Sema/vla-2.c.
2165 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002166 // Can this block be reached from the entrance?
Richard Smith7d02ca42019-05-06 04:14:01 +00002167 if (!cra->isReachable(&AC.getCFG()->getEntry(), block)) {
2168 AllReachable = false;
2169 break;
2170 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002171 }
Richard Smith7d02ca42019-05-06 04:14:01 +00002172 // If we cannot map to a basic block, assume the statement is
2173 // reachable.
Ted Kremenek3427fac2011-02-23 01:52:04 +00002174 }
Richard Smith7d02ca42019-05-06 04:14:01 +00002175
2176 if (AllReachable)
Ted Kremeneka099c592011-03-10 03:50:34 +00002177 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00002178 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002179 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002180
2181 if (!analyzed)
2182 flushDiagnostics(S, fscope);
2183 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002184
Ted Kremenek918fe842010-03-20 21:06:02 +00002185 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002186 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00002187 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002188 (isa<BlockDecl>(D)
2189 ? CheckFallThroughDiagnostics::MakeForBlock()
2190 : (isa<CXXMethodDecl>(D) &&
2191 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2192 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2193 ? CheckFallThroughDiagnostics::MakeForLambda()
Eric Fiselierda8f9b52017-05-25 02:16:53 +00002194 : (fscope->isCoroutine()
Eric Fiselier709d1b32016-10-27 07:30:31 +00002195 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2196 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Richard Smith2fdd95c2019-05-31 00:45:09 +00002197 CheckFallThroughForBody(S, D, Body, BlockType, CD, AC, fscope);
Ted Kremenek918fe842010-03-20 21:06:02 +00002198 }
2199
2200 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002201 if (P.enableCheckUnreachable) {
2202 // Only check for unreachable code on non-template instantiations.
2203 // Different template instantiations can effectively change the control-flow
2204 // and it is very difficult to prove that a snippet of code in a template
2205 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002206 bool isTemplateInstantiation = false;
2207 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2208 isTemplateInstantiation = Function->isTemplateInstantiation();
2209 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002210 CheckUnreachable(S, AC);
2211 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002212
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002213 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002214 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002215 SourceLocation FL = AC.getDecl()->getLocation();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002216 SourceLocation FEL = AC.getDecl()->getEndLoc();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002217 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002218 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002219 Reporter.setIssueBetaWarnings(true);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002220 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002221 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002222
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002223 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2224 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002225 Reporter.emitDiagnostics();
2226 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002227
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002228 // Check for violations of consumed properties.
2229 if (P.enableConsumedAnalysis) {
2230 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002231 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002232 Analyzer.run(AC);
2233 }
2234
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002235 if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
2236 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
Zequan Wu170b6862020-06-02 10:21:02 -07002237 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc()) ||
2238 !Diags.isIgnored(diag::warn_uninit_const_reference, D->getBeginLoc())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002239 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002240 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002241 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002242 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002243 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002244 reporter, stats);
2245
2246 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2247 ++NumUninitAnalysisFunctions;
2248 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2249 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2250 MaxUninitAnalysisVariablesPerFunction =
2251 std::max(MaxUninitAnalysisVariablesPerFunction,
2252 stats.NumVariablesAnalyzed);
2253 MaxUninitAnalysisBlockVisitsPerFunction =
2254 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2255 stats.NumBlockVisits);
2256 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002257 }
2258 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002259
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002260 bool FallThroughDiagFull =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002261 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002262 bool FallThroughDiagPerFunction = !Diags.isIgnored(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002263 diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
Richard Smith4f902c72016-03-08 00:32:55 +00002264 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2265 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002266 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002267 }
2268
John McCall460ce582015-10-22 18:38:17 +00002269 if (S.getLangOpts().ObjCWeak &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002270 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
Jordan Rose76831c62012-10-11 16:10:19 +00002271 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002272
Richard Trieu2f024f42013-12-21 02:33:43 +00002273
2274 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002275 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002276 D->getBeginLoc())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002277 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2278 checkRecursiveFunction(S, FD, Body, AC);
2279 }
2280 }
2281
Erich Keane89fe9c22017-06-23 20:22:19 +00002282 // Check for throw out of non-throwing function.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002283 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
Erich Keane89fe9c22017-06-23 20:22:19 +00002284 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2285 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2286 checkThrowInNonThrowingFunc(S, FD, AC);
2287
Richard Trieue9fa2662014-04-15 00:57:50 +00002288 // If none of the previous checks caused a CFG build, trigger one here
Richard Trieu8b0d14a2019-10-19 00:57:23 +00002289 // for the logical error handler.
2290 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00002291 AC.getCFG();
2292 }
2293
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002294 // Collect statistics about the CFG if it was built.
2295 if (S.CollectStats && AC.isCFGBuilt()) {
2296 ++NumFunctionsAnalyzed;
2297 if (CFG *cfg = AC.getCFG()) {
2298 // If we successfully built a CFG for this context, record some more
2299 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002300 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002301 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002302 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002303 } else {
2304 ++NumFunctionsWithBadCFGs;
2305 }
2306 }
2307}
2308
2309void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2310 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2311
2312 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2313 unsigned AvgCFGBlocksPerFunction =
2314 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2315 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2316 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2317 << " " << NumCFGBlocks << " CFG blocks built.\n"
2318 << " " << AvgCFGBlocksPerFunction
2319 << " average CFG blocks per function.\n"
2320 << " " << MaxCFGBlocksPerFunction
2321 << " max CFG blocks per function.\n";
2322
2323 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2324 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2325 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2326 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2327 llvm::errs() << NumUninitAnalysisFunctions
2328 << " functions analyzed for uninitialiazed variables\n"
2329 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2330 << " " << AvgUninitVariablesPerFunction
2331 << " average variables per function.\n"
2332 << " " << MaxUninitAnalysisVariablesPerFunction
2333 << " max variables per function.\n"
2334 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2335 << " " << AvgUninitBlockVisitsPerFunction
2336 << " average block visits per function.\n"
2337 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2338 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002339}