blob: 8a044d291444646bfcb70c3e920c07e4a503b891 [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 Trieuf935b562014-04-05 05:17:01 +0000162};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000163} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000164
Ted Kremenek918fe842010-03-20 21:06:02 +0000165//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000166// Check for infinite self-recursion in functions
167//===----------------------------------------------------------------------===//
168
Richard Trieu6995de92015-08-21 03:43:09 +0000169// Returns true if the function is called anywhere within the CFGBlock.
170// For member functions, the additional condition of being call from the
171// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000172static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000173 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000174 for (const auto &B : Block) {
175 if (B.getKind() != CFGElement::Statement)
176 continue;
177
178 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
179 if (!CE || !CE->getCalleeDecl() ||
180 CE->getCalleeDecl()->getCanonicalDecl() != FD)
181 continue;
182
183 // Skip function calls which are qualified with a templated class.
184 if (const DeclRefExpr *DRE =
185 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
186 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
187 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
188 isa<TemplateSpecializationType>(NNS->getAsType())) {
189 continue;
190 }
191 }
192 }
193
194 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
195 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
196 !MCE->getMethodDecl()->isVirtual())
197 return true;
198 }
199 return false;
200}
201
Robert Widmann97608442018-03-22 03:16:23 +0000202// Returns true if every path from the entry block passes through a call to FD.
Richard Trieu6995de92015-08-21 03:43:09 +0000203static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
Robert Widmann97608442018-03-22 03:16:23 +0000204 llvm::SmallPtrSet<CFGBlock *, 16> Visited;
205 llvm::SmallVector<CFGBlock *, 16> WorkList;
206 // Keep track of whether we found at least one recursive path.
207 bool foundRecursion = false;
Richard Trieu6995de92015-08-21 03:43:09 +0000208
209 const unsigned ExitID = cfg->getExit().getBlockID();
210
Robert Widmann97608442018-03-22 03:16:23 +0000211 // Seed the work list with the entry block.
212 WorkList.push_back(&cfg->getEntry());
Richard Trieu6995de92015-08-21 03:43:09 +0000213
Robert Widmann97608442018-03-22 03:16:23 +0000214 while (!WorkList.empty()) {
215 CFGBlock *Block = WorkList.pop_back_val();
Richard Trieu2f024f42013-12-21 02:33:43 +0000216
Robert Widmann97608442018-03-22 03:16:23 +0000217 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
218 if (CFGBlock *SuccBlock = *I) {
219 if (!Visited.insert(SuccBlock).second)
220 continue;
Richard Trieu2f024f42013-12-21 02:33:43 +0000221
Robert Widmann97608442018-03-22 03:16:23 +0000222 // Found a path to the exit node without a recursive call.
223 if (ExitID == SuccBlock->getBlockID())
224 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000225
Robert Widmann97608442018-03-22 03:16:23 +0000226 // If the successor block contains a recursive call, end analysis there.
227 if (hasRecursiveCallInPath(FD, *SuccBlock)) {
228 foundRecursion = true;
229 continue;
Richard Trieu6995de92015-08-21 03:43:09 +0000230 }
Richard Trieu6995de92015-08-21 03:43:09 +0000231
Robert Widmann97608442018-03-22 03:16:23 +0000232 WorkList.push_back(SuccBlock);
233 }
234 }
235 }
236 return foundRecursion;
Richard Trieu2f024f42013-12-21 02:33:43 +0000237}
238
239static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000240 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000241 FD = FD->getCanonicalDecl();
242
243 // Only run on non-templated functions and non-templated members of
244 // templated classes.
245 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
246 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
247 return;
248
249 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000250 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000251
Richard Trieu6995de92015-08-21 03:43:09 +0000252 // Emit diagnostic if a recursive function call is detected for all paths.
253 if (checkForRecursiveFunctionCall(FD, cfg))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000254 S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
Richard Trieu2f024f42013-12-21 02:33:43 +0000255}
256
257//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000258// Check for throw in a non-throwing function.
259//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000260
Richard Smith08482102018-02-20 02:32:30 +0000261/// Determine whether an exception thrown by E, unwinding from ThrowBlock,
262/// can reach ExitBlock.
263static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
264 CFG *Body) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000265 SmallVector<CFGBlock *, 16> Stack;
Richard Smith08482102018-02-20 02:32:30 +0000266 llvm::BitVector Queued(Body->getNumBlockIDs());
Erich Keane89fe9c22017-06-23 20:22:19 +0000267
Richard Smith08482102018-02-20 02:32:30 +0000268 Stack.push_back(&ThrowBlock);
269 Queued[ThrowBlock.getBlockID()] = true;
270
271 while (!Stack.empty()) {
272 CFGBlock &UnwindBlock = *Stack.back();
273 Stack.pop_back();
274
275 for (auto &Succ : UnwindBlock.succs()) {
276 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
Erich Keane89fe9c22017-06-23 20:22:19 +0000277 continue;
278
Richard Smith08482102018-02-20 02:32:30 +0000279 if (Succ->getBlockID() == Body->getExit().getBlockID())
280 return true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000281
Richard Smith08482102018-02-20 02:32:30 +0000282 if (auto *Catch =
283 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
284 QualType Caught = Catch->getCaughtType();
285 if (Caught.isNull() || // catch (...) catches everything
286 !E->getSubExpr() || // throw; is considered cuaght by any handler
287 S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
288 // Exception doesn't escape via this path.
289 break;
290 } else {
291 Stack.push_back(Succ);
292 Queued[Succ->getBlockID()] = true;
Erich Keane89fe9c22017-06-23 20:22:19 +0000293 }
Richard Smith08482102018-02-20 02:32:30 +0000294 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000295 }
Richard Smith08482102018-02-20 02:32:30 +0000296
297 return false;
298}
299
300static void visitReachableThrows(
301 CFG *BodyCFG,
302 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
303 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
304 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
305 for (CFGBlock *B : *BodyCFG) {
306 if (!Reachable[B->getBlockID()])
307 continue;
308 for (CFGElement &E : *B) {
309 Optional<CFGStmt> S = E.getAs<CFGStmt>();
310 if (!S)
311 continue;
312 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
313 Visit(Throw, *B);
314 }
315 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000316}
317
318static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
319 const FunctionDecl *FD) {
Erich Keane7538b352017-07-05 16:43:45 +0000320 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
321 FD->getTypeSourceInfo()) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000322 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
323 if (S.getLangOpts().CPlusPlus11 &&
324 (isa<CXXDestructorDecl>(FD) ||
325 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
Erich Keane7538b352017-07-05 16:43:45 +0000326 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
327 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
328 getAs<FunctionProtoType>())
329 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
330 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
331 << FD->getExceptionSpecSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +0000332 } else
Erich Keane7538b352017-07-05 16:43:45 +0000333 S.Diag(FD->getLocation(), diag::note_throw_in_function)
334 << FD->getExceptionSpecSourceRange();
Erich Keane89fe9c22017-06-23 20:22:19 +0000335 }
336}
337
338static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
339 AnalysisDeclContext &AC) {
340 CFG *BodyCFG = AC.getCFG();
341 if (!BodyCFG)
342 return;
343 if (BodyCFG->getExit().pred_empty())
344 return;
Richard Smith08482102018-02-20 02:32:30 +0000345 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
346 if (throwEscapes(S, Throw, Block, BodyCFG))
347 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
348 });
Erich Keane89fe9c22017-06-23 20:22:19 +0000349}
350
351static bool isNoexcept(const FunctionDecl *FD) {
352 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000353 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
Erich Keane89fe9c22017-06-23 20:22:19 +0000354 return true;
355 return false;
356}
357
358//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000359// Check for missing return value.
360//===----------------------------------------------------------------------===//
361
John McCall5c6ec8c2010-05-16 09:34:11 +0000362enum ControlFlowKind {
363 UnknownFallThrough,
364 NeverFallThrough,
365 MaybeFallThrough,
366 AlwaysFallThrough,
367 NeverFallThroughOrReturn
368};
Ted Kremenek918fe842010-03-20 21:06:02 +0000369
370/// CheckFallThrough - Check that we don't fall off the end of a
371/// Statement that should return a value.
372///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000373/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
374/// MaybeFallThrough iff we might or might not fall off the end,
375/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
376/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000377/// statement but we may return. We assume that functions not marked noreturn
378/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000379static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000380 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000381 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000382
383 // The CFG leaves in dead things, and we don't want the dead code paths to
384 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000385 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000386 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000387 live);
388
389 bool AddEHEdges = AC.getAddEHEdges();
390 if (!AddEHEdges && count != cfg->getNumBlockIDs())
391 // When there are things remaining dead, and we didn't add EH edges
392 // from CallExprs to the catch clauses, we have to go back and
393 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000394 for (const auto *B : *cfg) {
395 if (!live[B->getBlockID()]) {
396 if (B->pred_begin() == B->pred_end()) {
397 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000398 // When not adding EH edges from calls, catch clauses
399 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000400 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000401 continue;
402 }
403 }
404 }
405
406 // Now we know what is live, we check the live precessors of the exit block
407 // and look for fall through paths, being careful to ignore normal returns,
408 // and exceptional paths.
409 bool HasLiveReturn = false;
410 bool HasFakeEdge = false;
411 bool HasPlainEdge = false;
412 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000413
414 // Ignore default cases that aren't likely to be reachable because all
415 // enums in a switch(X) have explicit case statements.
416 CFGBlock::FilterOptions FO;
417 FO.IgnoreDefaultsWithCoveredEnums = 1;
418
Fangrui Song99337e22018-07-20 08:19:20 +0000419 for (CFGBlock::filtered_pred_iterator I =
420 cfg->getExit().filtered_pred_start_end(FO);
421 I.hasMore(); ++I) {
422 const CFGBlock &B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000423 if (!live[B.getBlockID()])
424 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000425
Chandler Carruth03faf782011-09-13 09:53:58 +0000426 // Skip blocks which contain an element marked as no-return. They don't
427 // represent actually viable edges into the exit block, so mark them as
428 // abnormal.
429 if (B.hasNoReturnElement()) {
430 HasAbnormalEdge = true;
431 continue;
432 }
433
Ted Kremenek5d068492011-01-26 04:49:52 +0000434 // Destructors can appear after the 'return' in the CFG. This is
435 // normal. We need to look pass the destructors for the return
436 // statement (if it exists).
437 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000438
Chandler Carruth03faf782011-09-13 09:53:58 +0000439 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000440 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000441 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000442
Ted Kremenek5d068492011-01-26 04:49:52 +0000443 // No more CFGElements in the block?
444 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000445 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
446 HasAbnormalEdge = true;
447 continue;
448 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000449 // A labeled empty statement, or the entry block...
450 HasPlainEdge = true;
451 continue;
452 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000453
David Blaikie2a01f5d2013-02-21 20:58:29 +0000454 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000455 const Stmt *S = CS.getStmt();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000456 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000457 HasLiveReturn = true;
458 continue;
459 }
460 if (isa<ObjCAtThrowStmt>(S)) {
461 HasFakeEdge = true;
462 continue;
463 }
464 if (isa<CXXThrowExpr>(S)) {
465 HasFakeEdge = true;
466 continue;
467 }
Chad Rosier32503022012-06-11 20:47:18 +0000468 if (isa<MSAsmStmt>(S)) {
469 // TODO: Verify this is correct.
470 HasFakeEdge = true;
471 HasLiveReturn = true;
472 continue;
473 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000474 if (isa<CXXTryStmt>(S)) {
475 HasAbnormalEdge = true;
476 continue;
477 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000478 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
479 == B.succ_end()) {
480 HasAbnormalEdge = true;
481 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000482 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000483
484 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000485 }
486 if (!HasPlainEdge) {
487 if (HasLiveReturn)
488 return NeverFallThrough;
489 return NeverFallThroughOrReturn;
490 }
491 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
492 return MaybeFallThrough;
493 // This says AlwaysFallThrough for calls to functions that are not marked
494 // noreturn, that don't return. If people would like this warning to be more
495 // accurate, such functions should be marked as noreturn.
496 return AlwaysFallThrough;
497}
498
Dan Gohman28ade552010-07-26 21:25:24 +0000499namespace {
500
Ted Kremenek918fe842010-03-20 21:06:02 +0000501struct CheckFallThroughDiagnostics {
502 unsigned diag_MaybeFallThrough_HasNoReturn;
503 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
504 unsigned diag_AlwaysFallThrough_HasNoReturn;
505 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
506 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000507 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000508 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000509
Douglas Gregor24f27692010-04-16 23:28:44 +0000510 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000511 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000512 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000513 D.diag_MaybeFallThrough_HasNoReturn =
514 diag::warn_falloff_noreturn_function;
515 D.diag_MaybeFallThrough_ReturnsNonVoid =
516 diag::warn_maybe_falloff_nonvoid_function;
517 D.diag_AlwaysFallThrough_HasNoReturn =
518 diag::warn_falloff_noreturn_function;
519 D.diag_AlwaysFallThrough_ReturnsNonVoid =
520 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000521
522 // Don't suggest that virtual functions be marked "noreturn", since they
523 // might be overridden by non-noreturn functions.
524 bool isVirtualMethod = false;
525 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
526 isVirtualMethod = Method->isVirtual();
Fangrui Song6907ce22018-07-30 19:24:48 +0000527
Douglas Gregor0de57202011-10-10 18:15:57 +0000528 // Don't suggest that template instantiations be marked "noreturn"
529 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000530 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
531 isTemplateInstantiation = Function->isTemplateInstantiation();
Fangrui Song6907ce22018-07-30 19:24:48 +0000532
Douglas Gregor0de57202011-10-10 18:15:57 +0000533 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000534 D.diag_NeverFallThroughOrReturn =
535 diag::warn_suggest_noreturn_function;
536 else
537 D.diag_NeverFallThroughOrReturn = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +0000538
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000539 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000540 return D;
541 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000542
Eric Fiselier709d1b32016-10-27 07:30:31 +0000543 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
544 CheckFallThroughDiagnostics D;
545 D.FuncLoc = Func->getLocation();
546 D.diag_MaybeFallThrough_HasNoReturn = 0;
547 D.diag_MaybeFallThrough_ReturnsNonVoid =
548 diag::warn_maybe_falloff_nonvoid_coroutine;
549 D.diag_AlwaysFallThrough_HasNoReturn = 0;
550 D.diag_AlwaysFallThrough_ReturnsNonVoid =
551 diag::warn_falloff_nonvoid_coroutine;
552 D.funMode = Coroutine;
553 return D;
554 }
555
Ted Kremenek918fe842010-03-20 21:06:02 +0000556 static CheckFallThroughDiagnostics MakeForBlock() {
557 CheckFallThroughDiagnostics D;
558 D.diag_MaybeFallThrough_HasNoReturn =
559 diag::err_noreturn_block_has_return_expr;
560 D.diag_MaybeFallThrough_ReturnsNonVoid =
561 diag::err_maybe_falloff_nonvoid_block;
562 D.diag_AlwaysFallThrough_HasNoReturn =
563 diag::err_noreturn_block_has_return_expr;
564 D.diag_AlwaysFallThrough_ReturnsNonVoid =
565 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000566 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000567 D.funMode = Block;
568 return D;
569 }
570
571 static CheckFallThroughDiagnostics MakeForLambda() {
572 CheckFallThroughDiagnostics D;
573 D.diag_MaybeFallThrough_HasNoReturn =
574 diag::err_noreturn_lambda_has_return_expr;
575 D.diag_MaybeFallThrough_ReturnsNonVoid =
576 diag::warn_maybe_falloff_nonvoid_lambda;
577 D.diag_AlwaysFallThrough_HasNoReturn =
578 diag::err_noreturn_lambda_has_return_expr;
579 D.diag_AlwaysFallThrough_ReturnsNonVoid =
580 diag::warn_falloff_nonvoid_lambda;
581 D.diag_NeverFallThroughOrReturn = 0;
582 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000583 return D;
584 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000585
David Blaikie9c902b52011-09-25 23:23:43 +0000586 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000587 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000588 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000589 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000590 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
591 FuncLoc)) &&
592 (!HasNoReturn ||
593 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
594 FuncLoc)) &&
595 (!ReturnsVoid ||
596 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000597 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000598 if (funMode == Coroutine) {
599 return (ReturnsVoid ||
600 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
601 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
602 FuncLoc)) &&
603 (!HasNoReturn);
604 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000605 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000606 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000607 }
608};
609
Hans Wennborgdcfba332015-10-06 23:40:43 +0000610} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000611
Reid Kleckner87a31802018-03-12 21:43:02 +0000612/// CheckFallThroughForBody - Check that we don't fall off the end of a
Ted Kremenek918fe842010-03-20 21:06:02 +0000613/// function that should return a value. Check that we don't fall off the end
614/// of a noreturn function. We assume that functions and blocks not marked
615/// noreturn will return.
616static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000617 const BlockExpr *blkExpr,
Reid Kleckner87a31802018-03-12 21:43:02 +0000618 const CheckFallThroughDiagnostics &CD,
619 AnalysisDeclContext &AC,
620 sema::FunctionScopeInfo *FSI) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000621
622 bool ReturnsVoid = false;
623 bool HasNoReturn = false;
Reid Kleckner87a31802018-03-12 21:43:02 +0000624 bool IsCoroutine = FSI->isCoroutine();
Ted Kremenek918fe842010-03-20 21:06:02 +0000625
Eric Fiselier709d1b32016-10-27 07:30:31 +0000626 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
627 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
628 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
629 else
630 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000631 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000632 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000633 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000634 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000635 HasNoReturn = MD->hasAttr<NoReturnAttr>();
636 }
637 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000638 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000639 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000640 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000641 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000642 ReturnsVoid = true;
643 if (FT->getNoReturnAttr())
644 HasNoReturn = true;
645 }
646 }
647
David Blaikie9c902b52011-09-25 23:23:43 +0000648 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000649
650 // Short circuit for compilation speed.
651 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
652 return;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000653 SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000654 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
655 if (IsCoroutine)
Reid Kleckner87a31802018-03-12 21:43:02 +0000656 S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000657 else
658 S.Diag(Loc, DiagID);
659 };
Erich Keane3efe0022018-07-20 14:13:28 +0000660
661 // cpu_dispatch functions permit empty function bodies for ICC compatibility.
662 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
663 return;
664
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000665 // Either in a function body compound statement, or a function-try-block.
666 switch (CheckFallThrough(AC)) {
667 case UnknownFallThrough:
668 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000669
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000670 case MaybeFallThrough:
671 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000672 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000673 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000674 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000675 break;
676 case AlwaysFallThrough:
677 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000678 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000679 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000680 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000681 break;
682 case NeverFallThroughOrReturn:
683 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
684 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
685 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
686 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
687 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
688 } else {
689 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000690 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000691 }
692 break;
693 case NeverFallThrough:
694 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000695 }
696}
697
698//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000699// -Wuninitialized
700//===----------------------------------------------------------------------===//
701
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000702namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000703/// ContainsReference - A visitor class to search for references to
704/// a particular declaration (the needle) within any evaluated component of an
705/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000706class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000707 bool FoundReference;
708 const DeclRefExpr *Needle;
709
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000710public:
Scott Douglass503fc392015-06-10 13:53:15 +0000711 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000712
Scott Douglass503fc392015-06-10 13:53:15 +0000713 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
714 : Inherited(Context), FoundReference(false), Needle(Needle) {}
715
716 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000717 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000718 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000719 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000720
Scott Douglass503fc392015-06-10 13:53:15 +0000721 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000722 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000723
Scott Douglass503fc392015-06-10 13:53:15 +0000724 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000725 if (E == Needle)
726 FoundReference = true;
727 else
Scott Douglass503fc392015-06-10 13:53:15 +0000728 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000729 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000730
731 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000732};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000733} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000734
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000735static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000736 QualType VariableTy = VD->getType().getCanonicalType();
737 if (VariableTy->isBlockPointerType() &&
738 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000739 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
740 << VD->getDeclName()
741 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000742 return true;
743 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000744
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000745 // Don't issue a fixit if there is already an initializer.
746 if (VD->getInit())
747 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000748
749 // Don't suggest a fixit inside macros.
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000750 if (VD->getEndLoc().isMacroID())
Richard Trieu2cdcf822012-05-03 01:09:59 +0000751 return false;
752
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000753 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000754
755 // Suggest possible initialization (if any).
756 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
757 if (Init.empty())
758 return false;
759
Richard Smith8d06f422012-01-12 23:53:29 +0000760 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
761 << FixItHint::CreateInsertion(Loc, Init);
762 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000763}
764
Richard Smith1bb8edb82012-05-26 06:20:46 +0000765/// Create a fixit to remove an if-like statement, on the assumption that its
766/// condition is CondVal.
767static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
768 const Stmt *Else, bool CondVal,
769 FixItHint &Fixit1, FixItHint &Fixit2) {
770 if (CondVal) {
771 // If condition is always true, remove all but the 'then'.
772 Fixit1 = FixItHint::CreateRemoval(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000773 CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000774 if (Else) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000775 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
776 Fixit2 =
777 FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000778 }
779 } else {
780 // If condition is always false, remove all but the 'else'.
781 if (Else)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000782 Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
783 If->getBeginLoc(), Else->getBeginLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000784 else
785 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
786 }
787}
788
789/// DiagUninitUse -- Helper function to produce a diagnostic for an
790/// uninitialized use of a variable.
791static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
792 bool IsCapturedByBlock) {
793 bool Diagnosed = false;
794
Richard Smithba8071e2013-09-12 18:49:10 +0000795 switch (Use.getKind()) {
796 case UninitUse::Always:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000797 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
Richard Smithba8071e2013-09-12 18:49:10 +0000798 << VD->getDeclName() << IsCapturedByBlock
799 << Use.getUser()->getSourceRange();
800 return;
801
802 case UninitUse::AfterDecl:
803 case UninitUse::AfterCall:
804 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
805 << VD->getDeclName() << IsCapturedByBlock
806 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
807 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
808 << VD->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000809 S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
810 << IsCapturedByBlock << Use.getUser()->getSourceRange();
Richard Smithba8071e2013-09-12 18:49:10 +0000811 return;
812
813 case UninitUse::Maybe:
814 case UninitUse::Sometimes:
815 // Carry on to report sometimes-uninitialized branches, if possible,
816 // or a 'may be used uninitialized' diagnostic otherwise.
817 break;
818 }
819
Richard Smith1bb8edb82012-05-26 06:20:46 +0000820 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000821 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
822 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000823 assert(Use.getKind() == UninitUse::Sometimes);
824
825 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000826 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000827
828 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000829 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000830 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000831 SourceRange Range;
832
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000833 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000834 // For all binary terminators, branch 0 is taken if the condition is true,
835 // and branch 1 is taken if the condition is false.
836 int RemoveDiagKind = -1;
837 const char *FixitStr =
838 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
839 : (I->Output ? "1" : "0");
840 FixItHint Fixit1, Fixit2;
841
Richard Smithba8071e2013-09-12 18:49:10 +0000842 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000843 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000844 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000845 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000846 continue;
847
848 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000849 case Stmt::IfStmtClass: {
850 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000851 DiagKind = 0;
852 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000853 Range = IS->getCond()->getSourceRange();
854 RemoveDiagKind = 0;
855 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
856 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000857 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000858 }
859 case Stmt::ConditionalOperatorClass: {
860 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000861 DiagKind = 0;
862 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000863 Range = CO->getCond()->getSourceRange();
864 RemoveDiagKind = 0;
865 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
866 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000867 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000868 }
Richard Smith4323bf82012-05-25 02:17:09 +0000869 case Stmt::BinaryOperatorClass: {
870 const BinaryOperator *BO = cast<BinaryOperator>(Term);
871 if (!BO->isLogicalOp())
872 continue;
873 DiagKind = 0;
874 Str = BO->getOpcodeStr();
875 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000876 RemoveDiagKind = 0;
877 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
878 (BO->getOpcode() == BO_LOr && !I->Output))
879 // true && y -> y, false || y -> y.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000880 Fixit1 = FixItHint::CreateRemoval(
881 SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
Richard Smith1bb8edb82012-05-26 06:20:46 +0000882 else
883 // false && y -> false, true || y -> true.
884 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000885 break;
886 }
887
888 // "loop is entered / loop is exited".
889 case Stmt::WhileStmtClass:
890 DiagKind = 1;
891 Str = "while";
892 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000893 RemoveDiagKind = 1;
894 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000895 break;
896 case Stmt::ForStmtClass:
897 DiagKind = 1;
898 Str = "for";
899 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000900 RemoveDiagKind = 1;
901 if (I->Output)
902 Fixit1 = FixItHint::CreateRemoval(Range);
903 else
904 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000905 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000906 case Stmt::CXXForRangeStmtClass:
907 if (I->Output == 1) {
908 // The use occurs if a range-based for loop's body never executes.
909 // That may be impossible, and there's no syntactic fix for this,
910 // so treat it as a 'may be uninitialized' case.
911 continue;
912 }
913 DiagKind = 1;
914 Str = "for";
915 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
916 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000917
918 // "condition is true / loop is exited".
919 case Stmt::DoStmtClass:
920 DiagKind = 2;
921 Str = "do";
922 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000923 RemoveDiagKind = 1;
924 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000925 break;
926
927 // "switch case is taken".
928 case Stmt::CaseStmtClass:
929 DiagKind = 3;
930 Str = "case";
931 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
932 break;
933 case Stmt::DefaultStmtClass:
934 DiagKind = 3;
935 Str = "default";
936 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
937 break;
938 }
939
Richard Smith1bb8edb82012-05-26 06:20:46 +0000940 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
941 << VD->getDeclName() << IsCapturedByBlock << DiagKind
942 << Str << I->Output << Range;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000943 S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
944 << IsCapturedByBlock << User->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000945 if (RemoveDiagKind != -1)
946 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
947 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
948
949 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000950 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000951
952 if (!Diagnosed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000953 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000954 << VD->getDeclName() << IsCapturedByBlock
955 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000956}
957
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000958/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
959/// uninitialized variable. This manages the different forms of diagnostic
960/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000961/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000962/// false.
963static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000964 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000965 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +0000966 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000967 // Inspect the initializer of the variable declaration which is
968 // being referenced prior to its initialization. We emit
969 // specialized diagnostics for self-initialization, and we
970 // specifically avoid warning about self references which take the
971 // form of:
972 //
973 // int x = x;
974 //
975 // This is used to indicate to GCC that 'x' is intentionally left
976 // uninitialized. Proven code paths which access 'x' in
977 // an uninitialized state after this will still warn.
978 if (const Expr *Initializer = VD->getInit()) {
979 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
980 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000981
Richard Trieu43a2fc72012-05-09 21:08:22 +0000982 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +0000983 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +0000984 if (CR.doesContainReference()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000985 S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
986 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
Richard Trieu43a2fc72012-05-09 21:08:22 +0000987 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000988 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000989 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000990
Richard Smith1bb8edb82012-05-26 06:20:46 +0000991 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000992 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000993 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000994 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000995 S.Diag(BE->getBeginLoc(),
Richard Smith1bb8edb82012-05-26 06:20:46 +0000996 diag::warn_uninit_byref_blockvar_captured_by_block)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000997 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000998 else
999 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +00001000 }
1001
1002 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +00001003 // the initializer of that declaration & we didn't already suggest
1004 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +00001005 if (!SuggestInitializationFixit(S, VD))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001006 S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
1007 << VD->getDeclName();
Chandler Carruth895904da2011-04-05 18:18:05 +00001008
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001009 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +00001010}
1011
Richard Smith84837d52012-05-03 18:27:39 +00001012namespace {
1013 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1014 public:
1015 FallthroughMapper(Sema &S)
1016 : FoundSwitchStatements(false),
1017 S(S) {
1018 }
1019
1020 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1021
1022 void markFallthroughVisited(const AttributedStmt *Stmt) {
1023 bool Found = FallthroughStmts.erase(Stmt);
1024 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +00001025 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +00001026 }
1027
1028 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1029
1030 const AttrStmts &getFallthroughStmts() const {
1031 return FallthroughStmts;
1032 }
1033
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001034 void fillReachableBlocks(CFG *Cfg) {
1035 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1036 std::deque<const CFGBlock *> BlockQueue;
1037
1038 ReachableBlocks.insert(&Cfg->getEntry());
1039 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001040 // Mark all case blocks reachable to avoid problems with switching on
1041 // constants, covered enums, etc.
1042 // These blocks can contain fall-through annotations, and we don't want to
1043 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +00001044 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001045 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +00001046 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001047 BlockQueue.push_back(B);
1048 }
1049
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001050 while (!BlockQueue.empty()) {
1051 const CFGBlock *P = BlockQueue.front();
1052 BlockQueue.pop_front();
1053 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1054 E = P->succ_end();
1055 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001056 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001057 BlockQueue.push_back(*I);
1058 }
1059 }
1060 }
1061
Richard Smith7532d372017-03-22 01:49:19 +00001062 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1063 bool IsTemplateInstantiation) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001064 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1065
Richard Smith84837d52012-05-03 18:27:39 +00001066 int UnannotatedCnt = 0;
1067 AnnotatedCnt = 0;
1068
Aaron Ballmane5195222014-05-15 20:50:47 +00001069 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +00001070 while (!BlockQueue.empty()) {
1071 const CFGBlock *P = BlockQueue.front();
1072 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +00001073 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +00001074
1075 const Stmt *Term = P->getTerminator();
1076 if (Term && isa<SwitchStmt>(Term))
1077 continue; // Switch statement, good.
1078
1079 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1080 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1081 continue; // Previous case label has no statements, good.
1082
Alexander Kornienko09f15f32013-01-25 20:44:56 +00001083 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1084 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1085 continue; // Case label is preceded with a normal label, good.
1086
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001087 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001088 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1089 ElemEnd = P->rend();
1090 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001091 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1092 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith7532d372017-03-22 01:49:19 +00001093 // Don't issue a warning for an unreachable fallthrough
1094 // attribute in template instantiations as it may not be
1095 // unreachable in all instantiations of the template.
1096 if (!IsTemplateInstantiation)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001097 S.Diag(AS->getBeginLoc(),
Richard Smith7532d372017-03-22 01:49:19 +00001098 diag::warn_fallthrough_attr_unreachable);
Richard Smith84837d52012-05-03 18:27:39 +00001099 markFallthroughVisited(AS);
1100 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001101 break;
Richard Smith84837d52012-05-03 18:27:39 +00001102 }
1103 // Don't care about other unreachable statements.
1104 }
1105 }
1106 // If there are no unreachable statements, this may be a special
1107 // case in CFG:
1108 // case X: {
1109 // A a; // A has a destructor.
1110 // break;
1111 // }
1112 // // <<<< This place is represented by a 'hanging' CFG block.
1113 // case Y:
1114 continue;
1115 }
1116
1117 const Stmt *LastStmt = getLastStmt(*P);
1118 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1119 markFallthroughVisited(AS);
1120 ++AnnotatedCnt;
1121 continue; // Fallthrough annotation, good.
1122 }
1123
1124 if (!LastStmt) { // This block contains no executable statements.
1125 // Traverse its predecessors.
1126 std::copy(P->pred_begin(), P->pred_end(),
1127 std::back_inserter(BlockQueue));
1128 continue;
1129 }
1130
1131 ++UnannotatedCnt;
1132 }
1133 return !!UnannotatedCnt;
1134 }
1135
1136 // RecursiveASTVisitor setup.
1137 bool shouldWalkTypesOfTypeLocs() const { return false; }
1138
1139 bool VisitAttributedStmt(AttributedStmt *S) {
1140 if (asFallThroughAttr(S))
1141 FallthroughStmts.insert(S);
1142 return true;
1143 }
1144
1145 bool VisitSwitchStmt(SwitchStmt *S) {
1146 FoundSwitchStatements = true;
1147 return true;
1148 }
1149
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001150 // We don't want to traverse local type declarations. We analyze their
1151 // methods separately.
1152 bool TraverseDecl(Decl *D) { return true; }
1153
Alexander Kornienkobf911642014-06-24 15:28:21 +00001154 // We analyze lambda bodies separately. Skip them here.
Sam McCalle60151c2019-01-14 10:31:42 +00001155 bool TraverseLambdaExpr(LambdaExpr *LE) {
1156 // Traverse the captures, but not the body.
1157 for (const auto &C : zip(LE->captures(), LE->capture_inits()))
1158 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
1159 return true;
1160 }
Alexander Kornienkobf911642014-06-24 15:28:21 +00001161
Richard Smith84837d52012-05-03 18:27:39 +00001162 private:
1163
1164 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1165 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1166 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1167 return AS;
1168 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001169 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001170 }
1171
1172 static const Stmt *getLastStmt(const CFGBlock &B) {
1173 if (const Stmt *Term = B.getTerminator())
1174 return Term;
1175 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1176 ElemEnd = B.rend();
1177 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001178 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1179 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001180 }
1181 // Workaround to detect a statement thrown out by CFGBuilder:
1182 // case X: {} case Y:
1183 // case X: ; case Y:
1184 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1185 if (!isa<SwitchCase>(SW->getSubStmt()))
1186 return SW->getSubStmt();
1187
Craig Topperc3ec1492014-05-26 06:22:03 +00001188 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001189 }
1190
1191 bool FoundSwitchStatements;
1192 AttrStmts FallthroughStmts;
1193 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001194 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001195 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001196} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001197
Richard Smith4f902c72016-03-08 00:32:55 +00001198static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1199 SourceLocation Loc) {
1200 TokenValue FallthroughTokens[] = {
1201 tok::l_square, tok::l_square,
1202 PP.getIdentifierInfo("fallthrough"),
1203 tok::r_square, tok::r_square
1204 };
1205
1206 TokenValue ClangFallthroughTokens[] = {
1207 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1208 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1209 tok::r_square, tok::r_square
1210 };
1211
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001212 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
Richard Smith4f902c72016-03-08 00:32:55 +00001213
1214 StringRef MacroName;
1215 if (PreferClangAttr)
1216 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1217 if (MacroName.empty())
1218 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1219 if (MacroName.empty() && !PreferClangAttr)
1220 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1221 if (MacroName.empty())
1222 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1223 return MacroName;
1224}
1225
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001226static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001227 bool PerFunction) {
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001228 // Only perform this analysis when using [[]] attributes. There is no good
1229 // workflow for this warning when not using C++11. There is no good way to
Fangrui Song6907ce22018-07-30 19:24:48 +00001230 // silence the warning (no attribute is available) unless we are using
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001231 // [[]] attributes. One could use pragmas to silence the warning, but as a
1232 // general solution that is gross and not in the spirit of this warning.
Ted Kremenekda5919f2012-11-12 21:20:48 +00001233 //
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001234 // NOTE: This an intermediate solution. There are on-going discussions on
Ted Kremenekda5919f2012-11-12 21:20:48 +00001235 // how to properly support this warning outside of C++11 with an annotation.
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001236 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001237 return;
1238
Richard Smith84837d52012-05-03 18:27:39 +00001239 FallthroughMapper FM(S);
1240 FM.TraverseStmt(AC.getBody());
1241
1242 if (!FM.foundSwitchStatements())
1243 return;
1244
Alexis Hunt2178f142012-06-15 21:22:05 +00001245 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001246 return;
1247
Richard Smith84837d52012-05-03 18:27:39 +00001248 CFG *Cfg = AC.getCFG();
1249
1250 if (!Cfg)
1251 return;
1252
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001253 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001254
Pete Cooper57d3f142015-07-30 17:22:52 +00001255 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001256 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001257
1258 if (!Label || !isa<SwitchCase>(Label))
1259 continue;
1260
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001261 int AnnotatedCnt;
1262
Richard Smith7532d372017-03-22 01:49:19 +00001263 bool IsTemplateInstantiation = false;
1264 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1265 IsTemplateInstantiation = Function->isTemplateInstantiation();
1266 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1267 IsTemplateInstantiation))
Richard Smith84837d52012-05-03 18:27:39 +00001268 continue;
1269
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001270 S.Diag(Label->getBeginLoc(),
1271 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1272 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001273
1274 if (!AnnotatedCnt) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001275 SourceLocation L = Label->getBeginLoc();
Richard Smith84837d52012-05-03 18:27:39 +00001276 if (L.isMacroID())
1277 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001278 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001279 const Stmt *Term = B->getTerminator();
1280 // Skip empty cases.
1281 while (B->empty() && !Term && B->succ_size() == 1) {
1282 B = *B->succ_begin();
1283 Term = B->getTerminator();
1284 }
1285 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001286 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001287 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001288 SmallString<64> TextToInsert(AnnotationSpelling);
1289 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001290 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001291 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001292 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001293 }
Richard Smith84837d52012-05-03 18:27:39 +00001294 }
1295 S.Diag(L, diag::note_insert_break_fixit) <<
1296 FixItHint::CreateInsertion(L, "break; ");
1297 }
1298 }
1299
Aaron Ballmane5195222014-05-15 20:50:47 +00001300 for (const auto *F : FM.getFallthroughStmts())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001301 S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001302}
1303
Jordan Rose25c0ea82012-10-29 17:46:47 +00001304static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1305 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001306 assert(S);
1307
1308 do {
1309 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001310 case Stmt::ForStmtClass:
1311 case Stmt::WhileStmtClass:
1312 case Stmt::CXXForRangeStmtClass:
1313 case Stmt::ObjCForCollectionStmtClass:
1314 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001315 case Stmt::DoStmtClass: {
Fangrui Song407659a2018-11-30 23:41:18 +00001316 Expr::EvalResult Result;
1317 if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx))
Jordan Rose25c0ea82012-10-29 17:46:47 +00001318 return true;
Fangrui Song407659a2018-11-30 23:41:18 +00001319 return Result.Val.getInt().getBoolValue();
Jordan Rose25c0ea82012-10-29 17:46:47 +00001320 }
Jordan Rose76831c62012-10-11 16:10:19 +00001321 default:
1322 break;
1323 }
1324 } while ((S = PM.getParent(S)));
1325
1326 return false;
1327}
1328
Jordan Rosed3934582012-09-28 22:21:30 +00001329static void diagnoseRepeatedUseOfWeak(Sema &S,
1330 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001331 const Decl *D,
1332 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001333 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1334 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1335 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001336 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1337 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001338
Jordan Rose25c0ea82012-10-29 17:46:47 +00001339 ASTContext &Ctx = S.getASTContext();
1340
Jordan Rosed3934582012-09-28 22:21:30 +00001341 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1342
1343 // Extract all weak objects that are referenced more than once.
1344 SmallVector<StmtUsesPair, 8> UsesByStmt;
1345 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1346 I != E; ++I) {
1347 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001348
1349 // Find the first read of the weak object.
1350 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1351 for ( ; UI != UE; ++UI) {
1352 if (UI->isUnsafe())
1353 break;
1354 }
1355
1356 // If there were only writes to this object, don't warn.
1357 if (UI == UE)
1358 continue;
1359
Jordan Rose76831c62012-10-11 16:10:19 +00001360 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001361 // read is not within a loop, don't warn. Additionally, don't warn in a
1362 // loop if the base object is a local variable -- local variables are often
1363 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001364 if (UI == Uses.begin()) {
1365 WeakUseVector::const_iterator UI2 = UI;
1366 for (++UI2; UI2 != UE; ++UI2)
1367 if (UI2->isUnsafe())
1368 break;
1369
Jordan Rose25c0ea82012-10-29 17:46:47 +00001370 if (UI2 == UE) {
1371 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001372 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001373
1374 const WeakObjectProfileTy &Profile = I->first;
1375 if (!Profile.isExactProfile())
1376 continue;
1377
1378 const NamedDecl *Base = Profile.getBase();
1379 if (!Base)
1380 Base = Profile.getProperty();
1381 assert(Base && "A profile always has a base or property.");
1382
1383 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1384 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1385 continue;
1386 }
Jordan Rose76831c62012-10-11 16:10:19 +00001387 }
1388
Jordan Rosed3934582012-09-28 22:21:30 +00001389 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1390 }
1391
1392 if (UsesByStmt.empty())
1393 return;
1394
1395 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001396 SourceManager &SM = S.getSourceManager();
Fangrui Song55fab262018-09-26 22:16:28 +00001397 llvm::sort(UsesByStmt,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001398 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001399 return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
1400 RHS.first->getBeginLoc());
1401 });
Jordan Rosed3934582012-09-28 22:21:30 +00001402
1403 // Classify the current code body for better warning text.
1404 // This enum should stay in sync with the cases in
1405 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1406 // FIXME: Should we use a common classification enum and the same set of
1407 // possibilities all throughout Sema?
1408 enum {
1409 Function,
1410 Method,
1411 Block,
1412 Lambda
1413 } FunctionKind;
1414
1415 if (isa<sema::BlockScopeInfo>(CurFn))
1416 FunctionKind = Block;
1417 else if (isa<sema::LambdaScopeInfo>(CurFn))
1418 FunctionKind = Lambda;
1419 else if (isa<ObjCMethodDecl>(D))
1420 FunctionKind = Method;
1421 else
1422 FunctionKind = Function;
1423
1424 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001425 for (const auto &P : UsesByStmt) {
1426 const Stmt *FirstRead = P.first;
1427 const WeakObjectProfileTy &Key = P.second->first;
1428 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001429
Jordan Rose657b5f42012-09-28 22:21:35 +00001430 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1431 // may not contain enough information to determine that these are different
1432 // properties. We can only be 100% sure of a repeated use in certain cases,
1433 // and we adjust the diagnostic kind accordingly so that the less certain
1434 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001435 unsigned DiagKind;
1436 if (Key.isExactProfile())
1437 DiagKind = diag::warn_arc_repeated_use_of_weak;
1438 else
1439 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1440
Jordan Rose657b5f42012-09-28 22:21:35 +00001441 // Classify the weak object being accessed for better warning text.
1442 // This enum should stay in sync with the cases in
1443 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1444 enum {
1445 Variable,
1446 Property,
1447 ImplicitProperty,
1448 Ivar
1449 } ObjectKind;
1450
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001451 const NamedDecl *KeyProp = Key.getProperty();
1452 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001453 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001454 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001455 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001456 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001457 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001458 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001459 ObjectKind = Ivar;
1460 else
1461 llvm_unreachable("Unexpected weak object kind!");
1462
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001463 // Do not warn about IBOutlet weak property receivers being set to null
1464 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001465 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001466 if (Prop->hasAttr<IBOutletAttr>())
1467 continue;
1468
Jordan Rosed3934582012-09-28 22:21:30 +00001469 // Show the first time the object was read.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001470 S.Diag(FirstRead->getBeginLoc(), DiagKind)
1471 << int(ObjectKind) << KeyProp << int(FunctionKind)
1472 << FirstRead->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001473
1474 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001475 for (const auto &Use : Uses) {
1476 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001477 continue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001478 S.Diag(Use.getUseExpr()->getBeginLoc(),
Jordan Rosed3934582012-09-28 22:21:30 +00001479 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001480 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001481 }
1482 }
1483}
1484
Jordan Rosed3934582012-09-28 22:21:30 +00001485namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001486class UninitValsDiagReporter : public UninitVariablesHandler {
1487 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001488 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001489 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001490 // Prefer using MapVector to DenseMap, so that iteration order will be
1491 // the same as insertion order. This is needed to obtain a deterministic
1492 // order of diagnostics when calling flushDiagnostics().
1493 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001494 UsesMap uses;
Fangrui Song6907ce22018-07-30 19:24:48 +00001495
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001496public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001497 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001498 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001499
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001500 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001501 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001502 if (!V.getPointer())
1503 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001504 return V;
1505 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001506
1507 void handleUseOfUninitVariable(const VarDecl *vd,
1508 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001509 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001510 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001511
Craig Toppere14c0f82014-03-12 04:55:44 +00001512 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001513 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001514 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001515
Ted Kremenek39fa0562011-01-21 19:41:41 +00001516 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001517 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001518 const VarDecl *vd = P.first;
1519 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001520
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001521 UsesVec *vec = V.getPointer();
1522 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001523
Fangrui Song6907ce22018-07-30 19:24:48 +00001524 // Specially handle the case where we have uses of an uninitialized
Ted Kremenek596fa162011-10-13 18:50:06 +00001525 // variable, but the root cause is an idiomatic self-init. We want
1526 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001527 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001528 DiagnoseUninitializedUse(S, vd,
1529 UninitUse(vd->getInit()->IgnoreParenCasts(),
1530 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001531 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001532 else {
1533 // Sort the uses by their SourceLocations. While not strictly
1534 // guaranteed to produce them in line/column order, this will provide
1535 // a stable ordering.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001536 llvm::sort(vec->begin(), vec->end(),
1537 [](const UninitUse &a, const UninitUse &b) {
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001538 // Prefer a more confident report over a less confident one.
1539 if (a.getKind() != b.getKind())
1540 return a.getKind() > b.getKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001541 return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001542 });
1543
Aaron Ballmane5195222014-05-15 20:50:47 +00001544 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001545 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001546 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001547
1548 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001549 // Skip further diagnostics for this variable. We try to warn only
1550 // on the first point at which a variable is used uninitialized.
1551 break;
1552 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001553 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001554
Ted Kremenek596fa162011-10-13 18:50:06 +00001555 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001556 delete vec;
1557 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001558
1559 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001560 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001561
1562private:
1563 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001564 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1565 return U.getKind() == UninitUse::Always ||
1566 U.getKind() == UninitUse::AfterCall ||
1567 U.getKind() == UninitUse::AfterDecl;
1568 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001569 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001570};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001571} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001572
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001573namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001574namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001575typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001576typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001577typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001578
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001579struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001580 SourceManager &SM;
1581 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001582
1583 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1584 // Although this call will be slow, this is only called when outputting
1585 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001586 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001587 }
1588};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001589} // anonymous namespace
1590} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001591
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001592//===----------------------------------------------------------------------===//
1593// -Wthread-safety
1594//===----------------------------------------------------------------------===//
1595namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001596namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001597namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001598class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001599 Sema &S;
1600 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001601 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001602
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001603 const FunctionDecl *CurrentFunction;
1604 bool Verbose;
1605
Aaron Ballman71291bc2014-08-15 12:38:17 +00001606 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001607 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001608 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001609 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001610 << CurrentFunction);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001611 return OptionalNotes(1, FNote);
1612 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001613 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001614 }
1615
Aaron Ballman71291bc2014-08-15 12:38:17 +00001616 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001617 OptionalNotes ONS(1, Note);
1618 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001619 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001620 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001621 << CurrentFunction);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001622 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001623 }
1624 return ONS;
1625 }
1626
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001627 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1628 const PartialDiagnosticAt &Note2) const {
1629 OptionalNotes ONS;
1630 ONS.push_back(Note1);
1631 ONS.push_back(Note2);
1632 if (Verbose && CurrentFunction) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001633 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001634 S.PDiag(diag::note_thread_warning_in_fun)
Richard Trieub4025802018-03-28 04:16:13 +00001635 << CurrentFunction);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001636 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001637 }
1638 return ONS;
1639 }
1640
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001641 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001642 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1643 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001644 // Gracefully handle rare cases when the analysis can't get a more
1645 // precise source location.
1646 if (!Loc.isValid())
1647 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001648 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001649 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001650 }
1651
1652 public:
Richard Smith92286672012-02-03 04:45:26 +00001653 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001654 : S(S), FunLocation(FL), FunEndLocation(FEL),
1655 CurrentFunction(nullptr), Verbose(false) {}
1656
1657 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001658
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001659 /// Emit all buffered diagnostics in order of sourcelocation.
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001660 /// We need to output diagnostics produced while iterating through
1661 /// the lockset in deterministic order, so this function orders diagnostics
1662 /// and outputs them.
1663 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001664 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001665 for (const auto &Diag : Warnings) {
1666 S.Diag(Diag.first.first, Diag.first.second);
1667 for (const auto &Note : Diag.second)
1668 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001669 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001670 }
1671
Aaron Ballmane0449042014-04-01 21:43:23 +00001672 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1673 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1674 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001675 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001676 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001677
Aaron Ballmane0449042014-04-01 21:43:23 +00001678 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1679 SourceLocation Loc) override {
1680 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001681 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001682
Aaron Ballmane0449042014-04-01 21:43:23 +00001683 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1684 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001685 SourceLocation Loc) override {
1686 if (Loc.isInvalid())
1687 Loc = FunLocation;
1688 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001689 << Kind << LockName << Received
1690 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001691 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001692 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001693
Aaron Ballmane0449042014-04-01 21:43:23 +00001694 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1695 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001696 }
1697
Aaron Ballmane0449042014-04-01 21:43:23 +00001698 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1699 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001700 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001701 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001702 unsigned DiagID = 0;
1703 switch (LEK) {
1704 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001705 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001706 break;
1707 case LEK_LockedSomeLoopIterations:
1708 DiagID = diag::warn_expecting_lock_held_on_loop;
1709 break;
1710 case LEK_LockedAtEndOfFunction:
1711 DiagID = diag::warn_no_unlock;
1712 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001713 case LEK_NotLockedAtEndOfFunction:
1714 DiagID = diag::warn_expecting_locked;
1715 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001716 }
Richard Smith92286672012-02-03 04:45:26 +00001717 if (LocEndOfScope.isInvalid())
1718 LocEndOfScope = FunEndLocation;
1719
Aaron Ballmane0449042014-04-01 21:43:23 +00001720 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1721 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001722 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001723 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1724 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001725 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001726 return;
1727 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001728 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001729 }
1730
Aaron Ballmane0449042014-04-01 21:43:23 +00001731 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1732 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001733 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001734 PartialDiagnosticAt Warning(Loc1,
1735 S.PDiag(diag::warn_lock_exclusive_and_shared)
1736 << Kind << LockName);
1737 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1738 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001739 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001740 }
1741
Aaron Ballmane0449042014-04-01 21:43:23 +00001742 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1743 ProtectedOperationKind POK, AccessKind AK,
1744 SourceLocation Loc) override {
1745 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1746 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001747 unsigned DiagID = POK == POK_VarAccess?
1748 diag::warn_variable_requires_any_lock:
1749 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001750 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
Richard Trieub4025802018-03-28 04:16:13 +00001751 << D << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001752 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001753 }
1754
Aaron Ballmane0449042014-04-01 21:43:23 +00001755 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1756 ProtectedOperationKind POK, Name LockName,
1757 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001758 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001759 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001760 if (PossibleMatch) {
1761 switch (POK) {
1762 case POK_VarAccess:
1763 DiagID = diag::warn_variable_requires_lock_precise;
1764 break;
1765 case POK_VarDereference:
1766 DiagID = diag::warn_var_deref_requires_lock_precise;
1767 break;
1768 case POK_FunctionCall:
1769 DiagID = diag::warn_fun_requires_lock_precise;
1770 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001771 case POK_PassByRef:
1772 DiagID = diag::warn_guarded_pass_by_reference;
1773 break;
1774 case POK_PtPassByRef:
1775 DiagID = diag::warn_pt_guarded_pass_by_reference;
1776 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001777 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001778 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
Richard Trieub4025802018-03-28 04:16:13 +00001779 << D
Aaron Ballmane0449042014-04-01 21:43:23 +00001780 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001781 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001782 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001783 if (Verbose && POK == POK_VarAccess) {
1784 PartialDiagnosticAt VNote(D->getLocation(),
1785 S.PDiag(diag::note_guarded_by_declared_here)
1786 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001787 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001788 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001789 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001790 } else {
1791 switch (POK) {
1792 case POK_VarAccess:
1793 DiagID = diag::warn_variable_requires_lock;
1794 break;
1795 case POK_VarDereference:
1796 DiagID = diag::warn_var_deref_requires_lock;
1797 break;
1798 case POK_FunctionCall:
1799 DiagID = diag::warn_fun_requires_lock;
1800 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001801 case POK_PassByRef:
1802 DiagID = diag::warn_guarded_pass_by_reference;
1803 break;
1804 case POK_PtPassByRef:
1805 DiagID = diag::warn_pt_guarded_pass_by_reference;
1806 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001807 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001808 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
Richard Trieub4025802018-03-28 04:16:13 +00001809 << D
Aaron Ballmane0449042014-04-01 21:43:23 +00001810 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001811 if (Verbose && POK == POK_VarAccess) {
1812 PartialDiagnosticAt Note(D->getLocation(),
Richard Trieub4025802018-03-28 04:16:13 +00001813 S.PDiag(diag::note_guarded_by_declared_here));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001814 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001815 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001816 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001817 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001818 }
1819
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001820 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1821 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001822 PartialDiagnosticAt Warning(Loc,
1823 S.PDiag(diag::warn_acquire_requires_negative_cap)
1824 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001825 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001826 }
1827
Aaron Ballmane0449042014-04-01 21:43:23 +00001828 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001829 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001830 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1831 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001832 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001833 }
1834
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001835 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1836 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001837 PartialDiagnosticAt Warning(Loc,
1838 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001839 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001840 }
1841
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001842 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001843 PartialDiagnosticAt Warning(Loc,
1844 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001845 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001846 }
1847
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001848 void enterFunction(const FunctionDecl* FD) override {
1849 CurrentFunction = FD;
1850 }
1851
1852 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001853 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001854 }
1855};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001856} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001857} // namespace threadSafety
1858} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001859
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001860//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001861// -Wconsumed
1862//===----------------------------------------------------------------------===//
1863
1864namespace clang {
1865namespace consumed {
1866namespace {
1867class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
Fangrui Song6907ce22018-07-30 19:24:48 +00001868
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001869 Sema &S;
1870 DiagList Warnings;
Fangrui Song6907ce22018-07-30 19:24:48 +00001871
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001872public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001873
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001874 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001875
1876 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001877 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001878 for (const auto &Diag : Warnings) {
1879 S.Diag(Diag.first.first, Diag.first.second);
1880 for (const auto &Note : Diag.second)
1881 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001882 }
1883 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001884
1885 void warnLoopStateMismatch(SourceLocation Loc,
1886 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001887 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1888 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001889
1890 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001891 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001892
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001893 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1894 StringRef VariableName,
1895 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001896 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001897
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001898 PartialDiagnosticAt Warning(Loc, S.PDiag(
1899 diag::warn_param_return_typestate_mismatch) << VariableName <<
1900 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001901
1902 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001903 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001904
DeLesley Hutchins69391772013-10-17 23:23:53 +00001905 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001906 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001907
DeLesley Hutchins69391772013-10-17 23:23:53 +00001908 PartialDiagnosticAt Warning(Loc, S.PDiag(
1909 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001910
1911 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001912 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001913
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001914 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001915 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001916 PartialDiagnosticAt Warning(Loc, S.PDiag(
1917 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001918
1919 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001920 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001921
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001922 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001923 StringRef ObservedState) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001924
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001925 PartialDiagnosticAt Warning(Loc, S.PDiag(
1926 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001927
1928 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001929 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001930
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001931 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001932 SourceLocation Loc) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001933
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001934 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001935 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001936
1937 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001938 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001939
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001940 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001941 StringRef State, SourceLocation Loc) override {
Fangrui Song6907ce22018-07-30 19:24:48 +00001942
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001943 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1944 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001945
1946 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001947 }
1948};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001949} // anonymous namespace
1950} // namespace consumed
1951} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001952
1953//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001954// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1955// warnings on a function, method, or block.
1956//===----------------------------------------------------------------------===//
1957
Ted Kremenek0b405322010-03-23 00:13:23 +00001958clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1959 enableCheckFallThrough = 1;
1960 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001961 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001962 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001963}
1964
Ted Kremenekad8753c2014-03-15 05:47:06 +00001965static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001966 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001967}
1968
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001969clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1970 : S(s),
1971 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001972 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001973 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001974 MaxCFGBlocksPerFunction(0),
1975 NumUninitAnalysisFunctions(0),
1976 NumUninitAnalysisVariables(0),
1977 MaxUninitAnalysisVariablesPerFunction(0),
1978 NumUninitAnalysisBlockVisits(0),
1979 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001980
1981 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001982 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001983
1984 DefaultPolicy.enableCheckUnreachable =
1985 isEnabled(D, warn_unreachable) ||
1986 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001987 isEnabled(D, warn_unreachable_return) ||
1988 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001989
1990 DefaultPolicy.enableThreadSafetyAnalysis =
1991 isEnabled(D, warn_double_lock);
1992
1993 DefaultPolicy.enableConsumedAnalysis =
1994 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001995}
1996
Aaron Ballmane5195222014-05-15 20:50:47 +00001997static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1998 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001999 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00002000}
2001
Ted Kremenek0b405322010-03-23 00:13:23 +00002002void clang::sema::
2003AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00002004 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00002005 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00002006
Ted Kremenek918fe842010-03-20 21:06:02 +00002007 // We avoid doing analysis-based warnings when there are errors for
2008 // two reasons:
2009 // (1) The CFGs often can't be constructed (if the body is invalid), so
2010 // don't bother trying.
2011 // (2) The code already has problems; running the analysis just takes more
2012 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00002013 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00002014
Olivier Goffart270ced22017-11-23 08:15:22 +00002015 // Do not do any analysis if we are going to just ignore them.
2016 if (Diags.getIgnoreAllWarnings() ||
2017 (Diags.getSuppressSystemWarnings() &&
2018 S.SourceMgr.isInSystemHeader(D->getLocation())))
Ted Kremenek0b405322010-03-23 00:13:23 +00002019 return;
2020
John McCall1d570a72010-08-25 05:56:39 +00002021 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00002022 if (cast<DeclContext>(D)->isDependentContext())
2023 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00002024
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002025 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002026 // Flush out any possibly unreachable diagnostics.
2027 flushDiagnostics(S, fscope);
2028 return;
2029 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002030
Ted Kremenek918fe842010-03-20 21:06:02 +00002031 const Stmt *Body = D->getBody();
2032 assert(Body);
2033
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002034 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00002035 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00002036
Ted Kremenek918fe842010-03-20 21:06:02 +00002037 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00002038 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00002039 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2040 AC.getCFGBuildOptions().AddEHEdges = false;
2041 AC.getCFGBuildOptions().AddInitializers = true;
2042 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002043 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00002044 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00002045 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002046
Ted Kremenek9e100ea2011-07-19 14:18:48 +00002047 // Force that certain expressions appear as CFGElements in the CFG. This
2048 // is used to speed up various analyses.
2049 // FIXME: This isn't the right factoring. This is here for initial
2050 // prototyping, but we need a way for analyses to say what expressions they
2051 // expect to always be CFGElements and then fill in the BuildOptions
2052 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002053 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2054 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002055 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00002056 AC.getCFGBuildOptions().setAllAlwaysAdd();
2057 }
2058 else {
2059 AC.getCFGBuildOptions()
2060 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00002061 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00002062 .setAlwaysAdd(Stmt::BlockExprClass)
2063 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2064 .setAlwaysAdd(Stmt::DeclRefExprClass)
2065 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00002066 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2067 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00002068 }
Ted Kremenek918fe842010-03-20 21:06:02 +00002069
Richard Trieue9fa2662014-04-15 00:57:50 +00002070 // Install the logical handler for -Wtautological-overlap-compare
George Burgess IVb65955e2018-08-05 01:37:07 +00002071 llvm::Optional<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002072 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002073 D->getBeginLoc())) {
George Burgess IVb65955e2018-08-05 01:37:07 +00002074 LEH.emplace(S);
2075 AC.getCFGBuildOptions().Observer = &*LEH;
Richard Trieuf935b562014-04-05 05:17:01 +00002076 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002077
Ted Kremenek3427fac2011-02-23 01:52:04 +00002078 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00002079 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002080 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00002081
2082 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00002083 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2084 if (D.stmt)
2085 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00002086 }
2087
2088 if (AC.getCFG()) {
2089 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00002090 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00002091 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00002092 if (D.stmt) {
2093 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00002094 CFGReverseBlockReachabilityAnalysis *cra =
2095 AC.getCFGReachablityAnalysis();
2096 // FIXME: We should be able to assert that block is non-null, but
2097 // the CFG analysis can skip potentially-evaluated expressions in
2098 // edge cases; see test/Sema/vla-2.c.
2099 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002100 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00002101 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00002102 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00002103 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00002104 }
2105 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002106 if (!processed) {
2107 // Emit the warning anyway if we cannot map to a basic block.
2108 S.Diag(D.Loc, D.PD);
2109 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002110 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002111 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002112
2113 if (!analyzed)
2114 flushDiagnostics(S, fscope);
2115 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002116
Ted Kremenek918fe842010-03-20 21:06:02 +00002117 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002118 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00002119 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002120 (isa<BlockDecl>(D)
2121 ? CheckFallThroughDiagnostics::MakeForBlock()
2122 : (isa<CXXMethodDecl>(D) &&
2123 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2124 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2125 ? CheckFallThroughDiagnostics::MakeForLambda()
Eric Fiselierda8f9b52017-05-25 02:16:53 +00002126 : (fscope->isCoroutine()
Eric Fiselier709d1b32016-10-27 07:30:31 +00002127 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2128 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Reid Kleckner87a31802018-03-12 21:43:02 +00002129 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
Ted Kremenek918fe842010-03-20 21:06:02 +00002130 }
2131
2132 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002133 if (P.enableCheckUnreachable) {
2134 // Only check for unreachable code on non-template instantiations.
2135 // Different template instantiations can effectively change the control-flow
2136 // and it is very difficult to prove that a snippet of code in a template
2137 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002138 bool isTemplateInstantiation = false;
2139 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2140 isTemplateInstantiation = Function->isTemplateInstantiation();
2141 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002142 CheckUnreachable(S, AC);
2143 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002144
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002145 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002146 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002147 SourceLocation FL = AC.getDecl()->getLocation();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002148 SourceLocation FEL = AC.getDecl()->getEndLoc();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002149 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002150 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002151 Reporter.setIssueBetaWarnings(true);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002152 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002153 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002154
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002155 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2156 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002157 Reporter.emitDiagnostics();
2158 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002159
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002160 // Check for violations of consumed properties.
2161 if (P.enableConsumedAnalysis) {
2162 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002163 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002164 Analyzer.run(AC);
2165 }
2166
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002167 if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
2168 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
2169 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002170 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002171 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002172 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002173 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002174 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002175 reporter, stats);
2176
2177 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2178 ++NumUninitAnalysisFunctions;
2179 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2180 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2181 MaxUninitAnalysisVariablesPerFunction =
2182 std::max(MaxUninitAnalysisVariablesPerFunction,
2183 stats.NumVariablesAnalyzed);
2184 MaxUninitAnalysisBlockVisitsPerFunction =
2185 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2186 stats.NumBlockVisits);
2187 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002188 }
2189 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002190
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002191 bool FallThroughDiagFull =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002192 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002193 bool FallThroughDiagPerFunction = !Diags.isIgnored(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002194 diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
Richard Smith4f902c72016-03-08 00:32:55 +00002195 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2196 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002197 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002198 }
2199
John McCall460ce582015-10-22 18:38:17 +00002200 if (S.getLangOpts().ObjCWeak &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002201 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
Jordan Rose76831c62012-10-11 16:10:19 +00002202 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002203
Richard Trieu2f024f42013-12-21 02:33:43 +00002204
2205 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002206 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002207 D->getBeginLoc())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002208 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2209 checkRecursiveFunction(S, FD, Body, AC);
2210 }
2211 }
2212
Erich Keane89fe9c22017-06-23 20:22:19 +00002213 // Check for throw out of non-throwing function.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002214 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
Erich Keane89fe9c22017-06-23 20:22:19 +00002215 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2216 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2217 checkThrowInNonThrowingFunc(S, FD, AC);
2218
Richard Trieue9fa2662014-04-15 00:57:50 +00002219 // If none of the previous checks caused a CFG build, trigger one here
2220 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002221 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002222 D->getBeginLoc())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00002223 AC.getCFG();
2224 }
2225
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002226 // Collect statistics about the CFG if it was built.
2227 if (S.CollectStats && AC.isCFGBuilt()) {
2228 ++NumFunctionsAnalyzed;
2229 if (CFG *cfg = AC.getCFG()) {
2230 // If we successfully built a CFG for this context, record some more
2231 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002232 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002233 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002234 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002235 } else {
2236 ++NumFunctionsWithBadCFGs;
2237 }
2238 }
2239}
2240
2241void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2242 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2243
2244 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2245 unsigned AvgCFGBlocksPerFunction =
2246 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2247 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2248 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2249 << " " << NumCFGBlocks << " CFG blocks built.\n"
2250 << " " << AvgCFGBlocksPerFunction
2251 << " average CFG blocks per function.\n"
2252 << " " << MaxCFGBlocksPerFunction
2253 << " max CFG blocks per function.\n";
2254
2255 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2256 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2257 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2258 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2259 llvm::errs() << NumUninitAnalysisFunctions
2260 << " functions analyzed for uninitialiazed variables\n"
2261 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2262 << " " << AvgUninitVariablesPerFunction
2263 << " average variables per function.\n"
2264 << " " << MaxUninitAnalysisVariablesPerFunction
2265 << " max variables per function.\n"
2266 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2267 << " " << AvgUninitBlockVisitsPerFunction
2268 << " average block visits per function.\n"
2269 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2270 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002271}