blob: e67f94c6383e022ad95721ab9212827503420182 [file] [log] [blame]
Ted Kremenek918fe842010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Rose76831c62012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smith84837d52012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
DeLesley Hutchins48a31762013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/ReachableCode.h"
30#include "clang/Analysis/Analyses/ThreadSafety.h"
31#include "clang/Analysis/Analyses/UninitializedValues.h"
George Karpenkov50657f62017-09-06 21:45:03 +000032#include "clang/Analysis/AnalysisDeclContext.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000033#include "clang/Analysis/CFG.h"
Ted Kremenek3427fac2011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Lex/Preprocessor.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000040#include "llvm/ADT/BitVector.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000041#include "llvm/ADT/MapVector.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000042#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000044#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000045#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000047#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000048#include <iterator>
Ted Kremenek918fe842010-03-20 21:06:02 +000049
50using namespace clang;
51
52//===----------------------------------------------------------------------===//
53// Unreachable code analysis.
54//===----------------------------------------------------------------------===//
55
56namespace {
57 class UnreachableCodeHandler : public reachable_code::Callback {
58 Sema &S;
Alex Lorenz569ad732017-01-12 10:48:03 +000059 SourceRange PreviousSilenceableCondVal;
60
Ted Kremenek918fe842010-03-20 21:06:02 +000061 public:
62 UnreachableCodeHandler(Sema &s) : S(s) {}
63
Ted Kremenek1a8641c2014-03-15 01:26:32 +000064 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000065 SourceLocation L,
66 SourceRange SilenceableCondVal,
67 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000068 SourceRange R2) override {
Alex Lorenz569ad732017-01-12 10:48:03 +000069 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
74 return;
75 PreviousSilenceableCondVal = SilenceableCondVal;
76
Ted Kremenek1a8641c2014-03-15 01:26:32 +000077 unsigned diag = diag::warn_unreachable;
78 switch (UK) {
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
81 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000082 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000083 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 break;
Ted Kremenek14210372014-03-21 06:02:36 +000085 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
87 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000088 case reachable_code::UK_Other:
89 break;
90 }
91
92 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000093
94 SourceLocation Open = SilenceableCondVal.getBegin();
95 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000096 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000098 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
102 }
103 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000104 }
105 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000106} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +0000107
108/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000109static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
114 //
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
118 return;
119
Ted Kremenek918fe842010-03-20 21:06:02 +0000120 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000122}
123
Benjamin Kramer3a002252015-02-16 16:53:12 +0000124namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000125/// \brief Warn on logical operator errors in CFGBuilder
126class LogicalErrorHandler : public CFGCallback {
127 Sema &S;
128
129public:
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
131
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
134 return true;
135
136 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000137 for (const Stmt *SubStmt : E->children())
138 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
139 if (HasMacroID(SubExpr))
140 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000141
142 return false;
143 }
144
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000146 if (HasMacroID(B))
147 return;
148
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
152 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000153
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000156 if (HasMacroID(B))
157 return;
158
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
162 }
Richard Trieuf935b562014-04-05 05:17:01 +0000163};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000164} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000165
Ted Kremenek918fe842010-03-20 21:06:02 +0000166//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000167// Check for infinite self-recursion in functions
168//===----------------------------------------------------------------------===//
169
Richard Trieu6995de92015-08-21 03:43:09 +0000170// Returns true if the function is called anywhere within the CFGBlock.
171// For member functions, the additional condition of being call from the
172// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000173static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000174 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000175 for (const auto &B : Block) {
176 if (B.getKind() != CFGElement::Statement)
177 continue;
178
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
182 continue;
183
184 // Skip function calls which are qualified with a templated class.
185 if (const DeclRefExpr *DRE =
186 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
187 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
188 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
189 isa<TemplateSpecializationType>(NNS->getAsType())) {
190 continue;
191 }
192 }
193 }
194
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
198 return true;
199 }
200 return false;
201}
202
Richard Trieu6995de92015-08-21 03:43:09 +0000203// All blocks are in one of three states. States are ordered so that blocks
204// can only move to higher states.
205enum RecursiveState {
206 FoundNoPath,
207 FoundPath,
208 FoundPathWithNoRecursiveCall
209};
210
211// Returns true if there exists a path to the exit block and every path
212// to the exit block passes through a call to FD.
213static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
214
215 const unsigned ExitID = cfg->getExit().getBlockID();
216
217 // Mark all nodes as FoundNoPath, then set the status of the entry block.
218 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
219 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
220
221 // Make the processing stack and seed it with the entry block.
222 SmallVector<CFGBlock *, 16> Stack;
223 Stack.push_back(&cfg->getEntry());
Richard Trieu2f024f42013-12-21 02:33:43 +0000224
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000225 while (!Stack.empty()) {
Richard Trieu6995de92015-08-21 03:43:09 +0000226 CFGBlock *CurBlock = Stack.back();
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000227 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000228
Richard Trieu6995de92015-08-21 03:43:09 +0000229 unsigned ID = CurBlock->getBlockID();
230 RecursiveState CurState = States[ID];
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000231
232 if (CurState == FoundPathWithNoRecursiveCall) {
233 // Found a path to the exit node without a recursive call.
234 if (ExitID == ID)
Richard Trieu6995de92015-08-21 03:43:09 +0000235 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000236
Richard Trieu6995de92015-08-21 03:43:09 +0000237 // Only change state if the block has a recursive call.
238 if (hasRecursiveCallInPath(FD, *CurBlock))
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000239 CurState = FoundPath;
240 }
241
Richard Trieu6995de92015-08-21 03:43:09 +0000242 // Loop over successor blocks and add them to the Stack if their state
243 // changes.
244 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
245 if (*I) {
246 unsigned next_ID = (*I)->getBlockID();
247 if (States[next_ID] < CurState) {
248 States[next_ID] = CurState;
249 Stack.push_back(*I);
250 }
251 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000252 }
Richard Trieu6995de92015-08-21 03:43:09 +0000253
254 // Return true if the exit node is reachable, and only reachable through
255 // a recursive call.
256 return States[ExitID] == FoundPath;
Richard Trieu2f024f42013-12-21 02:33:43 +0000257}
258
259static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000260 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000261 FD = FD->getCanonicalDecl();
262
263 // Only run on non-templated functions and non-templated members of
264 // templated classes.
265 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
266 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
267 return;
268
269 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000270 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000271
272 // If the exit block is unreachable, skip processing the function.
273 if (cfg->getExit().pred_empty())
274 return;
275
Richard Trieu6995de92015-08-21 03:43:09 +0000276 // Emit diagnostic if a recursive function call is detected for all paths.
277 if (checkForRecursiveFunctionCall(FD, cfg))
Richard Trieu2f024f42013-12-21 02:33:43 +0000278 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
279}
280
281//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000282// Check for throw in a non-throwing function.
283//===----------------------------------------------------------------------===//
284enum ThrowState {
285 FoundNoPathForThrow,
286 FoundPathForThrow,
287 FoundPathWithNoThrowOutFunction,
288};
289
Richard Smith56ae0a62018-01-13 05:05:45 +0000290static bool isThrowCaughtByHandlers(Sema &S,
291 const CXXThrowExpr *CE,
Erich Keane89fe9c22017-06-23 20:22:19 +0000292 const CXXTryStmt *TryStmt) {
293 for (unsigned H = 0, E = TryStmt->getNumHandlers(); H < E; ++H) {
Richard Smith56ae0a62018-01-13 05:05:45 +0000294 QualType Caught = TryStmt->getHandler(H)->getCaughtType();
295 if (Caught.isNull() || // catch (...) catches everything
296 (CE->getSubExpr() && // throw; is only caught by ...
297 S.handlerCanCatch(Caught, CE->getSubExpr()->getType())))
Erich Keane89fe9c22017-06-23 20:22:19 +0000298 return true;
299 }
300 return false;
301}
302
Richard Smith56ae0a62018-01-13 05:05:45 +0000303static bool doesThrowEscapePath(Sema &S, CFGBlock Block,
304 SourceLocation &OpLoc) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000305 for (const auto &B : Block) {
306 if (B.getKind() != CFGElement::Statement)
307 continue;
308 const auto *CE = dyn_cast<CXXThrowExpr>(B.getAs<CFGStmt>()->getStmt());
309 if (!CE)
310 continue;
311
312 OpLoc = CE->getThrowLoc();
313 for (const auto &I : Block.succs()) {
314 if (!I.isReachable())
315 continue;
316 if (const auto *Terminator =
317 dyn_cast_or_null<CXXTryStmt>(I->getTerminator()))
Richard Smith56ae0a62018-01-13 05:05:45 +0000318 if (isThrowCaughtByHandlers(S, CE, Terminator))
Erich Keane89fe9c22017-06-23 20:22:19 +0000319 return false;
320 }
321 return true;
322 }
323 return false;
324}
325
Richard Smith56ae0a62018-01-13 05:05:45 +0000326static bool hasThrowOutNonThrowingFunc(Sema &S, SourceLocation &OpLoc,
327 CFG *BodyCFG) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000328 unsigned ExitID = BodyCFG->getExit().getBlockID();
329
330 SmallVector<ThrowState, 16> States(BodyCFG->getNumBlockIDs(),
331 FoundNoPathForThrow);
332 States[BodyCFG->getEntry().getBlockID()] = FoundPathWithNoThrowOutFunction;
333
334 SmallVector<CFGBlock *, 16> Stack;
335 Stack.push_back(&BodyCFG->getEntry());
336 while (!Stack.empty()) {
Erich Keanecbb287c2017-10-17 17:45:21 +0000337 CFGBlock *CurBlock = Stack.pop_back_val();
Erich Keane89fe9c22017-06-23 20:22:19 +0000338
339 unsigned ID = CurBlock->getBlockID();
340 ThrowState CurState = States[ID];
341 if (CurState == FoundPathWithNoThrowOutFunction) {
342 if (ExitID == ID)
343 continue;
344
Richard Smith56ae0a62018-01-13 05:05:45 +0000345 if (doesThrowEscapePath(S, *CurBlock, OpLoc))
Erich Keane89fe9c22017-06-23 20:22:19 +0000346 CurState = FoundPathForThrow;
347 }
348
349 // Loop over successor blocks and add them to the Stack if their state
350 // changes.
351 for (const auto &I : CurBlock->succs())
352 if (I.isReachable()) {
353 unsigned NextID = I->getBlockID();
354 if (NextID == ExitID && CurState == FoundPathForThrow) {
355 States[NextID] = CurState;
356 } else if (States[NextID] < CurState) {
357 States[NextID] = CurState;
358 Stack.push_back(I);
359 }
360 }
361 }
362 // Return true if the exit node is reachable, and only reachable through
363 // a throw expression.
364 return States[ExitID] == FoundPathForThrow;
365}
366
367static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
368 const FunctionDecl *FD) {
Erich Keane7538b352017-07-05 16:43:45 +0000369 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
370 FD->getTypeSourceInfo()) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000371 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
372 if (S.getLangOpts().CPlusPlus11 &&
373 (isa<CXXDestructorDecl>(FD) ||
374 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
Erich Keane7538b352017-07-05 16:43:45 +0000375 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
376 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
377 getAs<FunctionProtoType>())
378 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
379 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
380 << FD->getExceptionSpecSourceRange();
381 } else
382 S.Diag(FD->getLocation(), diag::note_throw_in_function)
383 << FD->getExceptionSpecSourceRange();
Erich Keane89fe9c22017-06-23 20:22:19 +0000384 }
385}
386
387static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
388 AnalysisDeclContext &AC) {
389 CFG *BodyCFG = AC.getCFG();
390 if (!BodyCFG)
391 return;
392 if (BodyCFG->getExit().pred_empty())
393 return;
394 SourceLocation OpLoc;
Richard Smith56ae0a62018-01-13 05:05:45 +0000395 if (hasThrowOutNonThrowingFunc(S, OpLoc, BodyCFG))
Erich Keane89fe9c22017-06-23 20:22:19 +0000396 EmitDiagForCXXThrowInNonThrowingFunc(S, OpLoc, FD);
397}
398
399static bool isNoexcept(const FunctionDecl *FD) {
400 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Erich Keane9d10bdf2017-09-26 18:20:39 +0000401 if (FPT->isNothrow(FD->getASTContext()) || FD->hasAttr<NoThrowAttr>())
Erich Keane89fe9c22017-06-23 20:22:19 +0000402 return true;
403 return false;
404}
405
406//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000407// Check for missing return value.
408//===----------------------------------------------------------------------===//
409
John McCall5c6ec8c2010-05-16 09:34:11 +0000410enum ControlFlowKind {
411 UnknownFallThrough,
412 NeverFallThrough,
413 MaybeFallThrough,
414 AlwaysFallThrough,
415 NeverFallThroughOrReturn
416};
Ted Kremenek918fe842010-03-20 21:06:02 +0000417
418/// CheckFallThrough - Check that we don't fall off the end of a
419/// Statement that should return a value.
420///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000421/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
422/// MaybeFallThrough iff we might or might not fall off the end,
423/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
424/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000425/// statement but we may return. We assume that functions not marked noreturn
426/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000427static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000428 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000429 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000430
431 // The CFG leaves in dead things, and we don't want the dead code paths to
432 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000433 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000434 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000435 live);
436
437 bool AddEHEdges = AC.getAddEHEdges();
438 if (!AddEHEdges && count != cfg->getNumBlockIDs())
439 // When there are things remaining dead, and we didn't add EH edges
440 // from CallExprs to the catch clauses, we have to go back and
441 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000442 for (const auto *B : *cfg) {
443 if (!live[B->getBlockID()]) {
444 if (B->pred_begin() == B->pred_end()) {
445 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000446 // When not adding EH edges from calls, catch clauses
447 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000448 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000449 continue;
450 }
451 }
452 }
453
454 // Now we know what is live, we check the live precessors of the exit block
455 // and look for fall through paths, being careful to ignore normal returns,
456 // and exceptional paths.
457 bool HasLiveReturn = false;
458 bool HasFakeEdge = false;
459 bool HasPlainEdge = false;
460 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000461
462 // Ignore default cases that aren't likely to be reachable because all
463 // enums in a switch(X) have explicit case statements.
464 CFGBlock::FilterOptions FO;
465 FO.IgnoreDefaultsWithCoveredEnums = 1;
466
467 for (CFGBlock::filtered_pred_iterator
468 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
469 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000470 if (!live[B.getBlockID()])
471 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000472
Chandler Carruth03faf782011-09-13 09:53:58 +0000473 // Skip blocks which contain an element marked as no-return. They don't
474 // represent actually viable edges into the exit block, so mark them as
475 // abnormal.
476 if (B.hasNoReturnElement()) {
477 HasAbnormalEdge = true;
478 continue;
479 }
480
Ted Kremenek5d068492011-01-26 04:49:52 +0000481 // Destructors can appear after the 'return' in the CFG. This is
482 // normal. We need to look pass the destructors for the return
483 // statement (if it exists).
484 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000485
Chandler Carruth03faf782011-09-13 09:53:58 +0000486 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000487 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000488 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000489
Ted Kremenek5d068492011-01-26 04:49:52 +0000490 // No more CFGElements in the block?
491 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000492 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
493 HasAbnormalEdge = true;
494 continue;
495 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000496 // A labeled empty statement, or the entry block...
497 HasPlainEdge = true;
498 continue;
499 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000500
David Blaikie2a01f5d2013-02-21 20:58:29 +0000501 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000502 const Stmt *S = CS.getStmt();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000503 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000504 HasLiveReturn = true;
505 continue;
506 }
507 if (isa<ObjCAtThrowStmt>(S)) {
508 HasFakeEdge = true;
509 continue;
510 }
511 if (isa<CXXThrowExpr>(S)) {
512 HasFakeEdge = true;
513 continue;
514 }
Chad Rosier32503022012-06-11 20:47:18 +0000515 if (isa<MSAsmStmt>(S)) {
516 // TODO: Verify this is correct.
517 HasFakeEdge = true;
518 HasLiveReturn = true;
519 continue;
520 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000521 if (isa<CXXTryStmt>(S)) {
522 HasAbnormalEdge = true;
523 continue;
524 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000525 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
526 == B.succ_end()) {
527 HasAbnormalEdge = true;
528 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000529 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000530
531 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000532 }
533 if (!HasPlainEdge) {
534 if (HasLiveReturn)
535 return NeverFallThrough;
536 return NeverFallThroughOrReturn;
537 }
538 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
539 return MaybeFallThrough;
540 // This says AlwaysFallThrough for calls to functions that are not marked
541 // noreturn, that don't return. If people would like this warning to be more
542 // accurate, such functions should be marked as noreturn.
543 return AlwaysFallThrough;
544}
545
Dan Gohman28ade552010-07-26 21:25:24 +0000546namespace {
547
Ted Kremenek918fe842010-03-20 21:06:02 +0000548struct CheckFallThroughDiagnostics {
549 unsigned diag_MaybeFallThrough_HasNoReturn;
550 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
551 unsigned diag_AlwaysFallThrough_HasNoReturn;
552 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
553 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000554 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000555 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000556
Douglas Gregor24f27692010-04-16 23:28:44 +0000557 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000558 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000559 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000560 D.diag_MaybeFallThrough_HasNoReturn =
561 diag::warn_falloff_noreturn_function;
562 D.diag_MaybeFallThrough_ReturnsNonVoid =
563 diag::warn_maybe_falloff_nonvoid_function;
564 D.diag_AlwaysFallThrough_HasNoReturn =
565 diag::warn_falloff_noreturn_function;
566 D.diag_AlwaysFallThrough_ReturnsNonVoid =
567 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000568
569 // Don't suggest that virtual functions be marked "noreturn", since they
570 // might be overridden by non-noreturn functions.
571 bool isVirtualMethod = false;
572 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
573 isVirtualMethod = Method->isVirtual();
574
Douglas Gregor0de57202011-10-10 18:15:57 +0000575 // Don't suggest that template instantiations be marked "noreturn"
576 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000577 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
578 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000579
580 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000581 D.diag_NeverFallThroughOrReturn =
582 diag::warn_suggest_noreturn_function;
583 else
584 D.diag_NeverFallThroughOrReturn = 0;
585
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000586 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000587 return D;
588 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000589
Eric Fiselier709d1b32016-10-27 07:30:31 +0000590 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
591 CheckFallThroughDiagnostics D;
592 D.FuncLoc = Func->getLocation();
593 D.diag_MaybeFallThrough_HasNoReturn = 0;
594 D.diag_MaybeFallThrough_ReturnsNonVoid =
595 diag::warn_maybe_falloff_nonvoid_coroutine;
596 D.diag_AlwaysFallThrough_HasNoReturn = 0;
597 D.diag_AlwaysFallThrough_ReturnsNonVoid =
598 diag::warn_falloff_nonvoid_coroutine;
599 D.funMode = Coroutine;
600 return D;
601 }
602
Ted Kremenek918fe842010-03-20 21:06:02 +0000603 static CheckFallThroughDiagnostics MakeForBlock() {
604 CheckFallThroughDiagnostics D;
605 D.diag_MaybeFallThrough_HasNoReturn =
606 diag::err_noreturn_block_has_return_expr;
607 D.diag_MaybeFallThrough_ReturnsNonVoid =
608 diag::err_maybe_falloff_nonvoid_block;
609 D.diag_AlwaysFallThrough_HasNoReturn =
610 diag::err_noreturn_block_has_return_expr;
611 D.diag_AlwaysFallThrough_ReturnsNonVoid =
612 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000613 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000614 D.funMode = Block;
615 return D;
616 }
617
618 static CheckFallThroughDiagnostics MakeForLambda() {
619 CheckFallThroughDiagnostics D;
620 D.diag_MaybeFallThrough_HasNoReturn =
621 diag::err_noreturn_lambda_has_return_expr;
622 D.diag_MaybeFallThrough_ReturnsNonVoid =
623 diag::warn_maybe_falloff_nonvoid_lambda;
624 D.diag_AlwaysFallThrough_HasNoReturn =
625 diag::err_noreturn_lambda_has_return_expr;
626 D.diag_AlwaysFallThrough_ReturnsNonVoid =
627 diag::warn_falloff_nonvoid_lambda;
628 D.diag_NeverFallThroughOrReturn = 0;
629 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000630 return D;
631 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000632
David Blaikie9c902b52011-09-25 23:23:43 +0000633 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000634 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000635 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000636 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000637 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
638 FuncLoc)) &&
639 (!HasNoReturn ||
640 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
641 FuncLoc)) &&
642 (!ReturnsVoid ||
643 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000644 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000645 if (funMode == Coroutine) {
646 return (ReturnsVoid ||
647 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
648 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
649 FuncLoc)) &&
650 (!HasNoReturn);
651 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000652 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000653 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000654 }
655};
656
Hans Wennborgdcfba332015-10-06 23:40:43 +0000657} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000658
Ted Kremenek918fe842010-03-20 21:06:02 +0000659/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
660/// function that should return a value. Check that we don't fall off the end
661/// of a noreturn function. We assume that functions and blocks not marked
662/// noreturn will return.
663static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000664 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000665 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000666 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000667
668 bool ReturnsVoid = false;
669 bool HasNoReturn = false;
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000670 bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
Ted Kremenek918fe842010-03-20 21:06:02 +0000671
Eric Fiselier709d1b32016-10-27 07:30:31 +0000672 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
673 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
674 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
675 else
676 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000677 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000678 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000679 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000680 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000681 HasNoReturn = MD->hasAttr<NoReturnAttr>();
682 }
683 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000684 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000685 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000686 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000687 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000688 ReturnsVoid = true;
689 if (FT->getNoReturnAttr())
690 HasNoReturn = true;
691 }
692 }
693
David Blaikie9c902b52011-09-25 23:23:43 +0000694 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000695
696 // Short circuit for compilation speed.
697 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
698 return;
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000699 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000700 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
701 if (IsCoroutine)
702 S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
703 else
704 S.Diag(Loc, DiagID);
705 };
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000706 // Either in a function body compound statement, or a function-try-block.
707 switch (CheckFallThrough(AC)) {
708 case UnknownFallThrough:
709 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000710
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000711 case MaybeFallThrough:
712 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000713 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000714 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000715 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000716 break;
717 case AlwaysFallThrough:
718 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000719 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000720 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000721 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000722 break;
723 case NeverFallThroughOrReturn:
724 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
725 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
726 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
727 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
728 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
729 } else {
730 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000731 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000732 }
733 break;
734 case NeverFallThrough:
735 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000736 }
737}
738
739//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000740// -Wuninitialized
741//===----------------------------------------------------------------------===//
742
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000743namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000744/// ContainsReference - A visitor class to search for references to
745/// a particular declaration (the needle) within any evaluated component of an
746/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000747class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000748 bool FoundReference;
749 const DeclRefExpr *Needle;
750
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000751public:
Scott Douglass503fc392015-06-10 13:53:15 +0000752 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000753
Scott Douglass503fc392015-06-10 13:53:15 +0000754 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
755 : Inherited(Context), FoundReference(false), Needle(Needle) {}
756
757 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000758 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000759 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000760 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000761
Scott Douglass503fc392015-06-10 13:53:15 +0000762 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000763 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000764
Scott Douglass503fc392015-06-10 13:53:15 +0000765 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000766 if (E == Needle)
767 FoundReference = true;
768 else
Scott Douglass503fc392015-06-10 13:53:15 +0000769 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000770 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000771
772 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000773};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000774} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000775
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000776static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000777 QualType VariableTy = VD->getType().getCanonicalType();
778 if (VariableTy->isBlockPointerType() &&
779 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000780 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
781 << VD->getDeclName()
782 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000783 return true;
784 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000785
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000786 // Don't issue a fixit if there is already an initializer.
787 if (VD->getInit())
788 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000789
790 // Don't suggest a fixit inside macros.
791 if (VD->getLocEnd().isMacroID())
792 return false;
793
Alp Tokerb6cc5922014-05-03 03:45:55 +0000794 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000795
796 // Suggest possible initialization (if any).
797 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
798 if (Init.empty())
799 return false;
800
Richard Smith8d06f422012-01-12 23:53:29 +0000801 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
802 << FixItHint::CreateInsertion(Loc, Init);
803 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000804}
805
Richard Smith1bb8edb82012-05-26 06:20:46 +0000806/// Create a fixit to remove an if-like statement, on the assumption that its
807/// condition is CondVal.
808static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
809 const Stmt *Else, bool CondVal,
810 FixItHint &Fixit1, FixItHint &Fixit2) {
811 if (CondVal) {
812 // If condition is always true, remove all but the 'then'.
813 Fixit1 = FixItHint::CreateRemoval(
814 CharSourceRange::getCharRange(If->getLocStart(),
815 Then->getLocStart()));
816 if (Else) {
Craig Topper07fa1762015-11-15 02:31:46 +0000817 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000818 Fixit2 = FixItHint::CreateRemoval(
819 SourceRange(ElseKwLoc, Else->getLocEnd()));
820 }
821 } else {
822 // If condition is always false, remove all but the 'else'.
823 if (Else)
824 Fixit1 = FixItHint::CreateRemoval(
825 CharSourceRange::getCharRange(If->getLocStart(),
826 Else->getLocStart()));
827 else
828 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
829 }
830}
831
832/// DiagUninitUse -- Helper function to produce a diagnostic for an
833/// uninitialized use of a variable.
834static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
835 bool IsCapturedByBlock) {
836 bool Diagnosed = false;
837
Richard Smithba8071e2013-09-12 18:49:10 +0000838 switch (Use.getKind()) {
839 case UninitUse::Always:
840 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
841 << VD->getDeclName() << IsCapturedByBlock
842 << Use.getUser()->getSourceRange();
843 return;
844
845 case UninitUse::AfterDecl:
846 case UninitUse::AfterCall:
847 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
848 << VD->getDeclName() << IsCapturedByBlock
849 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
850 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
851 << VD->getSourceRange();
852 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
853 << IsCapturedByBlock << Use.getUser()->getSourceRange();
854 return;
855
856 case UninitUse::Maybe:
857 case UninitUse::Sometimes:
858 // Carry on to report sometimes-uninitialized branches, if possible,
859 // or a 'may be used uninitialized' diagnostic otherwise.
860 break;
861 }
862
Richard Smith1bb8edb82012-05-26 06:20:46 +0000863 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000864 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
865 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000866 assert(Use.getKind() == UninitUse::Sometimes);
867
868 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000869 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000870
871 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000872 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000873 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000874 SourceRange Range;
875
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000876 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000877 // For all binary terminators, branch 0 is taken if the condition is true,
878 // and branch 1 is taken if the condition is false.
879 int RemoveDiagKind = -1;
880 const char *FixitStr =
881 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
882 : (I->Output ? "1" : "0");
883 FixItHint Fixit1, Fixit2;
884
Richard Smithba8071e2013-09-12 18:49:10 +0000885 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000886 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000887 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000888 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000889 continue;
890
891 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000892 case Stmt::IfStmtClass: {
893 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000894 DiagKind = 0;
895 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000896 Range = IS->getCond()->getSourceRange();
897 RemoveDiagKind = 0;
898 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
899 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000900 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000901 }
902 case Stmt::ConditionalOperatorClass: {
903 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000904 DiagKind = 0;
905 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000906 Range = CO->getCond()->getSourceRange();
907 RemoveDiagKind = 0;
908 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
909 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000910 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000911 }
Richard Smith4323bf82012-05-25 02:17:09 +0000912 case Stmt::BinaryOperatorClass: {
913 const BinaryOperator *BO = cast<BinaryOperator>(Term);
914 if (!BO->isLogicalOp())
915 continue;
916 DiagKind = 0;
917 Str = BO->getOpcodeStr();
918 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000919 RemoveDiagKind = 0;
920 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
921 (BO->getOpcode() == BO_LOr && !I->Output))
922 // true && y -> y, false || y -> y.
923 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
924 BO->getOperatorLoc()));
925 else
926 // false && y -> false, true || y -> true.
927 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000928 break;
929 }
930
931 // "loop is entered / loop is exited".
932 case Stmt::WhileStmtClass:
933 DiagKind = 1;
934 Str = "while";
935 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000936 RemoveDiagKind = 1;
937 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000938 break;
939 case Stmt::ForStmtClass:
940 DiagKind = 1;
941 Str = "for";
942 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000943 RemoveDiagKind = 1;
944 if (I->Output)
945 Fixit1 = FixItHint::CreateRemoval(Range);
946 else
947 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000948 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000949 case Stmt::CXXForRangeStmtClass:
950 if (I->Output == 1) {
951 // The use occurs if a range-based for loop's body never executes.
952 // That may be impossible, and there's no syntactic fix for this,
953 // so treat it as a 'may be uninitialized' case.
954 continue;
955 }
956 DiagKind = 1;
957 Str = "for";
958 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
959 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000960
961 // "condition is true / loop is exited".
962 case Stmt::DoStmtClass:
963 DiagKind = 2;
964 Str = "do";
965 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000966 RemoveDiagKind = 1;
967 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000968 break;
969
970 // "switch case is taken".
971 case Stmt::CaseStmtClass:
972 DiagKind = 3;
973 Str = "case";
974 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
975 break;
976 case Stmt::DefaultStmtClass:
977 DiagKind = 3;
978 Str = "default";
979 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
980 break;
981 }
982
Richard Smith1bb8edb82012-05-26 06:20:46 +0000983 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
984 << VD->getDeclName() << IsCapturedByBlock << DiagKind
985 << Str << I->Output << Range;
986 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
987 << IsCapturedByBlock << User->getSourceRange();
988 if (RemoveDiagKind != -1)
989 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
990 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
991
992 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000993 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000994
995 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000996 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000997 << VD->getDeclName() << IsCapturedByBlock
998 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000999}
1000
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001001/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
1002/// uninitialized variable. This manages the different forms of diagnostic
1003/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +00001004/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001005/// false.
1006static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +00001007 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +00001008 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +00001009 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +00001010 // Inspect the initializer of the variable declaration which is
1011 // being referenced prior to its initialization. We emit
1012 // specialized diagnostics for self-initialization, and we
1013 // specifically avoid warning about self references which take the
1014 // form of:
1015 //
1016 // int x = x;
1017 //
1018 // This is used to indicate to GCC that 'x' is intentionally left
1019 // uninitialized. Proven code paths which access 'x' in
1020 // an uninitialized state after this will still warn.
1021 if (const Expr *Initializer = VD->getInit()) {
1022 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1023 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +00001024
Richard Trieu43a2fc72012-05-09 21:08:22 +00001025 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +00001026 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +00001027 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +00001028 S.Diag(DRE->getLocStart(),
1029 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +00001030 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1031 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +00001032 }
Chandler Carruth895904da2011-04-05 18:18:05 +00001033 }
Richard Trieu43a2fc72012-05-09 21:08:22 +00001034
Richard Smith1bb8edb82012-05-26 06:20:46 +00001035 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +00001036 } else {
Richard Smith4323bf82012-05-25 02:17:09 +00001037 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +00001038 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1039 S.Diag(BE->getLocStart(),
1040 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +00001041 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +00001042 else
1043 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +00001044 }
1045
1046 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +00001047 // the initializer of that declaration & we didn't already suggest
1048 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +00001049 if (!SuggestInitializationFixit(S, VD))
Reid Klecknerf463a8a2016-04-29 00:37:43 +00001050 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
Chandler Carruth895904da2011-04-05 18:18:05 +00001051 << VD->getDeclName();
1052
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001053 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +00001054}
1055
Richard Smith84837d52012-05-03 18:27:39 +00001056namespace {
1057 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1058 public:
1059 FallthroughMapper(Sema &S)
1060 : FoundSwitchStatements(false),
1061 S(S) {
1062 }
1063
1064 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1065
1066 void markFallthroughVisited(const AttributedStmt *Stmt) {
1067 bool Found = FallthroughStmts.erase(Stmt);
1068 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +00001069 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +00001070 }
1071
1072 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1073
1074 const AttrStmts &getFallthroughStmts() const {
1075 return FallthroughStmts;
1076 }
1077
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001078 void fillReachableBlocks(CFG *Cfg) {
1079 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1080 std::deque<const CFGBlock *> BlockQueue;
1081
1082 ReachableBlocks.insert(&Cfg->getEntry());
1083 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001084 // Mark all case blocks reachable to avoid problems with switching on
1085 // constants, covered enums, etc.
1086 // These blocks can contain fall-through annotations, and we don't want to
1087 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +00001088 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001089 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +00001090 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001091 BlockQueue.push_back(B);
1092 }
1093
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001094 while (!BlockQueue.empty()) {
1095 const CFGBlock *P = BlockQueue.front();
1096 BlockQueue.pop_front();
1097 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1098 E = P->succ_end();
1099 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001100 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001101 BlockQueue.push_back(*I);
1102 }
1103 }
1104 }
1105
Richard Smith7532d372017-03-22 01:49:19 +00001106 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1107 bool IsTemplateInstantiation) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001108 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1109
Richard Smith84837d52012-05-03 18:27:39 +00001110 int UnannotatedCnt = 0;
1111 AnnotatedCnt = 0;
1112
Aaron Ballmane5195222014-05-15 20:50:47 +00001113 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +00001114 while (!BlockQueue.empty()) {
1115 const CFGBlock *P = BlockQueue.front();
1116 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +00001117 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +00001118
1119 const Stmt *Term = P->getTerminator();
1120 if (Term && isa<SwitchStmt>(Term))
1121 continue; // Switch statement, good.
1122
1123 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1124 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1125 continue; // Previous case label has no statements, good.
1126
Alexander Kornienko09f15f32013-01-25 20:44:56 +00001127 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1128 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1129 continue; // Case label is preceded with a normal label, good.
1130
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001131 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001132 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1133 ElemEnd = P->rend();
1134 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001135 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1136 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith7532d372017-03-22 01:49:19 +00001137 // Don't issue a warning for an unreachable fallthrough
1138 // attribute in template instantiations as it may not be
1139 // unreachable in all instantiations of the template.
1140 if (!IsTemplateInstantiation)
1141 S.Diag(AS->getLocStart(),
1142 diag::warn_fallthrough_attr_unreachable);
Richard Smith84837d52012-05-03 18:27:39 +00001143 markFallthroughVisited(AS);
1144 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001145 break;
Richard Smith84837d52012-05-03 18:27:39 +00001146 }
1147 // Don't care about other unreachable statements.
1148 }
1149 }
1150 // If there are no unreachable statements, this may be a special
1151 // case in CFG:
1152 // case X: {
1153 // A a; // A has a destructor.
1154 // break;
1155 // }
1156 // // <<<< This place is represented by a 'hanging' CFG block.
1157 // case Y:
1158 continue;
1159 }
1160
1161 const Stmt *LastStmt = getLastStmt(*P);
1162 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1163 markFallthroughVisited(AS);
1164 ++AnnotatedCnt;
1165 continue; // Fallthrough annotation, good.
1166 }
1167
1168 if (!LastStmt) { // This block contains no executable statements.
1169 // Traverse its predecessors.
1170 std::copy(P->pred_begin(), P->pred_end(),
1171 std::back_inserter(BlockQueue));
1172 continue;
1173 }
1174
1175 ++UnannotatedCnt;
1176 }
1177 return !!UnannotatedCnt;
1178 }
1179
1180 // RecursiveASTVisitor setup.
1181 bool shouldWalkTypesOfTypeLocs() const { return false; }
1182
1183 bool VisitAttributedStmt(AttributedStmt *S) {
1184 if (asFallThroughAttr(S))
1185 FallthroughStmts.insert(S);
1186 return true;
1187 }
1188
1189 bool VisitSwitchStmt(SwitchStmt *S) {
1190 FoundSwitchStatements = true;
1191 return true;
1192 }
1193
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001194 // We don't want to traverse local type declarations. We analyze their
1195 // methods separately.
1196 bool TraverseDecl(Decl *D) { return true; }
1197
Alexander Kornienkobf911642014-06-24 15:28:21 +00001198 // We analyze lambda bodies separately. Skip them here.
1199 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1200
Richard Smith84837d52012-05-03 18:27:39 +00001201 private:
1202
1203 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1204 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1205 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1206 return AS;
1207 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001208 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001209 }
1210
1211 static const Stmt *getLastStmt(const CFGBlock &B) {
1212 if (const Stmt *Term = B.getTerminator())
1213 return Term;
1214 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1215 ElemEnd = B.rend();
1216 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001217 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1218 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001219 }
1220 // Workaround to detect a statement thrown out by CFGBuilder:
1221 // case X: {} case Y:
1222 // case X: ; case Y:
1223 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1224 if (!isa<SwitchCase>(SW->getSubStmt()))
1225 return SW->getSubStmt();
1226
Craig Topperc3ec1492014-05-26 06:22:03 +00001227 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001228 }
1229
1230 bool FoundSwitchStatements;
1231 AttrStmts FallthroughStmts;
1232 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001233 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001234 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001235} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001236
Richard Smith4f902c72016-03-08 00:32:55 +00001237static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1238 SourceLocation Loc) {
1239 TokenValue FallthroughTokens[] = {
1240 tok::l_square, tok::l_square,
1241 PP.getIdentifierInfo("fallthrough"),
1242 tok::r_square, tok::r_square
1243 };
1244
1245 TokenValue ClangFallthroughTokens[] = {
1246 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1247 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1248 tok::r_square, tok::r_square
1249 };
1250
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001251 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
Richard Smith4f902c72016-03-08 00:32:55 +00001252
1253 StringRef MacroName;
1254 if (PreferClangAttr)
1255 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1256 if (MacroName.empty())
1257 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1258 if (MacroName.empty() && !PreferClangAttr)
1259 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1260 if (MacroName.empty())
1261 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1262 return MacroName;
1263}
1264
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001265static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001266 bool PerFunction) {
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001267 // Only perform this analysis when using [[]] attributes. There is no good
1268 // workflow for this warning when not using C++11. There is no good way to
1269 // silence the warning (no attribute is available) unless we are using
1270 // [[]] attributes. One could use pragmas to silence the warning, but as a
1271 // general solution that is gross and not in the spirit of this warning.
Ted Kremenekda5919f2012-11-12 21:20:48 +00001272 //
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001273 // NOTE: This an intermediate solution. There are on-going discussions on
Ted Kremenekda5919f2012-11-12 21:20:48 +00001274 // how to properly support this warning outside of C++11 with an annotation.
Aaron Ballman8c6b1a32017-10-18 14:33:27 +00001275 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001276 return;
1277
Richard Smith84837d52012-05-03 18:27:39 +00001278 FallthroughMapper FM(S);
1279 FM.TraverseStmt(AC.getBody());
1280
1281 if (!FM.foundSwitchStatements())
1282 return;
1283
Alexis Hunt2178f142012-06-15 21:22:05 +00001284 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001285 return;
1286
Richard Smith84837d52012-05-03 18:27:39 +00001287 CFG *Cfg = AC.getCFG();
1288
1289 if (!Cfg)
1290 return;
1291
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001292 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001293
Pete Cooper57d3f142015-07-30 17:22:52 +00001294 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001295 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001296
1297 if (!Label || !isa<SwitchCase>(Label))
1298 continue;
1299
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001300 int AnnotatedCnt;
1301
Richard Smith7532d372017-03-22 01:49:19 +00001302 bool IsTemplateInstantiation = false;
1303 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1304 IsTemplateInstantiation = Function->isTemplateInstantiation();
1305 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1306 IsTemplateInstantiation))
Richard Smith84837d52012-05-03 18:27:39 +00001307 continue;
1308
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001309 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001310 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1311 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001312
1313 if (!AnnotatedCnt) {
1314 SourceLocation L = Label->getLocStart();
1315 if (L.isMacroID())
1316 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001317 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001318 const Stmt *Term = B->getTerminator();
1319 // Skip empty cases.
1320 while (B->empty() && !Term && B->succ_size() == 1) {
1321 B = *B->succ_begin();
1322 Term = B->getTerminator();
1323 }
1324 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001325 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001326 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001327 SmallString<64> TextToInsert(AnnotationSpelling);
1328 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001329 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001330 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001331 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001332 }
Richard Smith84837d52012-05-03 18:27:39 +00001333 }
1334 S.Diag(L, diag::note_insert_break_fixit) <<
1335 FixItHint::CreateInsertion(L, "break; ");
1336 }
1337 }
1338
Aaron Ballmane5195222014-05-15 20:50:47 +00001339 for (const auto *F : FM.getFallthroughStmts())
Richard Smith4f902c72016-03-08 00:32:55 +00001340 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001341}
1342
Jordan Rose25c0ea82012-10-29 17:46:47 +00001343static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1344 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001345 assert(S);
1346
1347 do {
1348 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001349 case Stmt::ForStmtClass:
1350 case Stmt::WhileStmtClass:
1351 case Stmt::CXXForRangeStmtClass:
1352 case Stmt::ObjCForCollectionStmtClass:
1353 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001354 case Stmt::DoStmtClass: {
1355 const Expr *Cond = cast<DoStmt>(S)->getCond();
1356 llvm::APSInt Val;
1357 if (!Cond->EvaluateAsInt(Val, Ctx))
1358 return true;
1359 return Val.getBoolValue();
1360 }
Jordan Rose76831c62012-10-11 16:10:19 +00001361 default:
1362 break;
1363 }
1364 } while ((S = PM.getParent(S)));
1365
1366 return false;
1367}
1368
Jordan Rosed3934582012-09-28 22:21:30 +00001369static void diagnoseRepeatedUseOfWeak(Sema &S,
1370 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001371 const Decl *D,
1372 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001373 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1374 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1375 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001376 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1377 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001378
Jordan Rose25c0ea82012-10-29 17:46:47 +00001379 ASTContext &Ctx = S.getASTContext();
1380
Jordan Rosed3934582012-09-28 22:21:30 +00001381 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1382
1383 // Extract all weak objects that are referenced more than once.
1384 SmallVector<StmtUsesPair, 8> UsesByStmt;
1385 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1386 I != E; ++I) {
1387 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001388
1389 // Find the first read of the weak object.
1390 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1391 for ( ; UI != UE; ++UI) {
1392 if (UI->isUnsafe())
1393 break;
1394 }
1395
1396 // If there were only writes to this object, don't warn.
1397 if (UI == UE)
1398 continue;
1399
Jordan Rose76831c62012-10-11 16:10:19 +00001400 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001401 // read is not within a loop, don't warn. Additionally, don't warn in a
1402 // loop if the base object is a local variable -- local variables are often
1403 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001404 if (UI == Uses.begin()) {
1405 WeakUseVector::const_iterator UI2 = UI;
1406 for (++UI2; UI2 != UE; ++UI2)
1407 if (UI2->isUnsafe())
1408 break;
1409
Jordan Rose25c0ea82012-10-29 17:46:47 +00001410 if (UI2 == UE) {
1411 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001412 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001413
1414 const WeakObjectProfileTy &Profile = I->first;
1415 if (!Profile.isExactProfile())
1416 continue;
1417
1418 const NamedDecl *Base = Profile.getBase();
1419 if (!Base)
1420 Base = Profile.getProperty();
1421 assert(Base && "A profile always has a base or property.");
1422
1423 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1424 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1425 continue;
1426 }
Jordan Rose76831c62012-10-11 16:10:19 +00001427 }
1428
Jordan Rosed3934582012-09-28 22:21:30 +00001429 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1430 }
1431
1432 if (UsesByStmt.empty())
1433 return;
1434
1435 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001436 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001437 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001438 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1439 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1440 RHS.first->getLocStart());
1441 });
Jordan Rosed3934582012-09-28 22:21:30 +00001442
1443 // Classify the current code body for better warning text.
1444 // This enum should stay in sync with the cases in
1445 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1446 // FIXME: Should we use a common classification enum and the same set of
1447 // possibilities all throughout Sema?
1448 enum {
1449 Function,
1450 Method,
1451 Block,
1452 Lambda
1453 } FunctionKind;
1454
1455 if (isa<sema::BlockScopeInfo>(CurFn))
1456 FunctionKind = Block;
1457 else if (isa<sema::LambdaScopeInfo>(CurFn))
1458 FunctionKind = Lambda;
1459 else if (isa<ObjCMethodDecl>(D))
1460 FunctionKind = Method;
1461 else
1462 FunctionKind = Function;
1463
1464 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001465 for (const auto &P : UsesByStmt) {
1466 const Stmt *FirstRead = P.first;
1467 const WeakObjectProfileTy &Key = P.second->first;
1468 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001469
Jordan Rose657b5f42012-09-28 22:21:35 +00001470 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1471 // may not contain enough information to determine that these are different
1472 // properties. We can only be 100% sure of a repeated use in certain cases,
1473 // and we adjust the diagnostic kind accordingly so that the less certain
1474 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001475 unsigned DiagKind;
1476 if (Key.isExactProfile())
1477 DiagKind = diag::warn_arc_repeated_use_of_weak;
1478 else
1479 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1480
Jordan Rose657b5f42012-09-28 22:21:35 +00001481 // Classify the weak object being accessed for better warning text.
1482 // This enum should stay in sync with the cases in
1483 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1484 enum {
1485 Variable,
1486 Property,
1487 ImplicitProperty,
1488 Ivar
1489 } ObjectKind;
1490
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001491 const NamedDecl *KeyProp = Key.getProperty();
1492 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001493 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001494 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001495 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001496 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001497 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001498 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001499 ObjectKind = Ivar;
1500 else
1501 llvm_unreachable("Unexpected weak object kind!");
1502
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001503 // Do not warn about IBOutlet weak property receivers being set to null
1504 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001505 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001506 if (Prop->hasAttr<IBOutletAttr>())
1507 continue;
1508
Jordan Rosed3934582012-09-28 22:21:30 +00001509 // Show the first time the object was read.
1510 S.Diag(FirstRead->getLocStart(), DiagKind)
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001511 << int(ObjectKind) << KeyProp << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001512 << FirstRead->getSourceRange();
1513
1514 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001515 for (const auto &Use : Uses) {
1516 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001517 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001518 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001519 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001520 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001521 }
1522 }
1523}
1524
Jordan Rosed3934582012-09-28 22:21:30 +00001525namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001526class UninitValsDiagReporter : public UninitVariablesHandler {
1527 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001528 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001529 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001530 // Prefer using MapVector to DenseMap, so that iteration order will be
1531 // the same as insertion order. This is needed to obtain a deterministic
1532 // order of diagnostics when calling flushDiagnostics().
1533 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001534 UsesMap uses;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001535
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001536public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001537 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001538 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001539
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001540 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001541 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001542 if (!V.getPointer())
1543 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001544 return V;
1545 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001546
1547 void handleUseOfUninitVariable(const VarDecl *vd,
1548 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001549 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001550 }
1551
Craig Toppere14c0f82014-03-12 04:55:44 +00001552 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001553 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001554 }
1555
1556 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001557 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001558 const VarDecl *vd = P.first;
1559 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001560
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001561 UsesVec *vec = V.getPointer();
1562 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001563
1564 // Specially handle the case where we have uses of an uninitialized
1565 // variable, but the root cause is an idiomatic self-init. We want
1566 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001567 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001568 DiagnoseUninitializedUse(S, vd,
1569 UninitUse(vd->getInit()->IgnoreParenCasts(),
1570 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001571 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001572 else {
1573 // Sort the uses by their SourceLocations. While not strictly
1574 // guaranteed to produce them in line/column order, this will provide
1575 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001576 std::sort(vec->begin(), vec->end(),
1577 [](const UninitUse &a, const UninitUse &b) {
1578 // Prefer a more confident report over a less confident one.
1579 if (a.getKind() != b.getKind())
1580 return a.getKind() > b.getKind();
1581 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1582 });
1583
Aaron Ballmane5195222014-05-15 20:50:47 +00001584 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001585 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001586 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001587
1588 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001589 // Skip further diagnostics for this variable. We try to warn only
1590 // on the first point at which a variable is used uninitialized.
1591 break;
1592 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001593 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001594
1595 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001596 delete vec;
1597 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001598
1599 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001600 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001601
1602private:
1603 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001604 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1605 return U.getKind() == UninitUse::Always ||
1606 U.getKind() == UninitUse::AfterCall ||
1607 U.getKind() == UninitUse::AfterDecl;
1608 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001609 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001610};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001611} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001612
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001613namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001614namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001615typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001616typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001617typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001618
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001619struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001620 SourceManager &SM;
1621 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001622
1623 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1624 // Although this call will be slow, this is only called when outputting
1625 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001626 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001627 }
1628};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001629} // anonymous namespace
1630} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001631
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001632//===----------------------------------------------------------------------===//
1633// -Wthread-safety
1634//===----------------------------------------------------------------------===//
1635namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001636namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001637namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001638class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001639 Sema &S;
1640 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001641 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001642
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001643 const FunctionDecl *CurrentFunction;
1644 bool Verbose;
1645
Aaron Ballman71291bc2014-08-15 12:38:17 +00001646 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001647 if (Verbose && CurrentFunction) {
1648 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001649 S.PDiag(diag::note_thread_warning_in_fun)
1650 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001651 return OptionalNotes(1, FNote);
1652 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001653 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001654 }
1655
Aaron Ballman71291bc2014-08-15 12:38:17 +00001656 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001657 OptionalNotes ONS(1, Note);
1658 if (Verbose && CurrentFunction) {
1659 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001660 S.PDiag(diag::note_thread_warning_in_fun)
1661 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001662 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001663 }
1664 return ONS;
1665 }
1666
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001667 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1668 const PartialDiagnosticAt &Note2) const {
1669 OptionalNotes ONS;
1670 ONS.push_back(Note1);
1671 ONS.push_back(Note2);
1672 if (Verbose && CurrentFunction) {
1673 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1674 S.PDiag(diag::note_thread_warning_in_fun)
1675 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001676 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001677 }
1678 return ONS;
1679 }
1680
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001681 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001682 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1683 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001684 // Gracefully handle rare cases when the analysis can't get a more
1685 // precise source location.
1686 if (!Loc.isValid())
1687 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001688 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001689 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001690 }
1691
1692 public:
Richard Smith92286672012-02-03 04:45:26 +00001693 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001694 : S(S), FunLocation(FL), FunEndLocation(FEL),
1695 CurrentFunction(nullptr), Verbose(false) {}
1696
1697 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001698
1699 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1700 /// We need to output diagnostics produced while iterating through
1701 /// the lockset in deterministic order, so this function orders diagnostics
1702 /// and outputs them.
1703 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001704 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001705 for (const auto &Diag : Warnings) {
1706 S.Diag(Diag.first.first, Diag.first.second);
1707 for (const auto &Note : Diag.second)
1708 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001709 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001710 }
1711
Aaron Ballmane0449042014-04-01 21:43:23 +00001712 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1713 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1714 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001715 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001716 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001717
Aaron Ballmane0449042014-04-01 21:43:23 +00001718 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1719 SourceLocation Loc) override {
1720 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001721 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001722
Aaron Ballmane0449042014-04-01 21:43:23 +00001723 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1724 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001725 SourceLocation Loc) override {
1726 if (Loc.isInvalid())
1727 Loc = FunLocation;
1728 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001729 << Kind << LockName << Received
1730 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001731 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001732 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001733
Aaron Ballmane0449042014-04-01 21:43:23 +00001734 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1735 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001736 }
1737
Aaron Ballmane0449042014-04-01 21:43:23 +00001738 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1739 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001740 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001741 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001742 unsigned DiagID = 0;
1743 switch (LEK) {
1744 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001745 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001746 break;
1747 case LEK_LockedSomeLoopIterations:
1748 DiagID = diag::warn_expecting_lock_held_on_loop;
1749 break;
1750 case LEK_LockedAtEndOfFunction:
1751 DiagID = diag::warn_no_unlock;
1752 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001753 case LEK_NotLockedAtEndOfFunction:
1754 DiagID = diag::warn_expecting_locked;
1755 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001756 }
Richard Smith92286672012-02-03 04:45:26 +00001757 if (LocEndOfScope.isInvalid())
1758 LocEndOfScope = FunEndLocation;
1759
Aaron Ballmane0449042014-04-01 21:43:23 +00001760 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1761 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001762 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001763 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1764 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001765 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001766 return;
1767 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001768 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001769 }
1770
Aaron Ballmane0449042014-04-01 21:43:23 +00001771 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1772 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001773 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001774 PartialDiagnosticAt Warning(Loc1,
1775 S.PDiag(diag::warn_lock_exclusive_and_shared)
1776 << Kind << LockName);
1777 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1778 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001779 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001780 }
1781
Aaron Ballmane0449042014-04-01 21:43:23 +00001782 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1783 ProtectedOperationKind POK, AccessKind AK,
1784 SourceLocation Loc) override {
1785 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1786 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001787 unsigned DiagID = POK == POK_VarAccess?
1788 diag::warn_variable_requires_any_lock:
1789 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001790 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001791 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001792 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001793 }
1794
Aaron Ballmane0449042014-04-01 21:43:23 +00001795 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1796 ProtectedOperationKind POK, Name LockName,
1797 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001798 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001799 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001800 if (PossibleMatch) {
1801 switch (POK) {
1802 case POK_VarAccess:
1803 DiagID = diag::warn_variable_requires_lock_precise;
1804 break;
1805 case POK_VarDereference:
1806 DiagID = diag::warn_var_deref_requires_lock_precise;
1807 break;
1808 case POK_FunctionCall:
1809 DiagID = diag::warn_fun_requires_lock_precise;
1810 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001811 case POK_PassByRef:
1812 DiagID = diag::warn_guarded_pass_by_reference;
1813 break;
1814 case POK_PtPassByRef:
1815 DiagID = diag::warn_pt_guarded_pass_by_reference;
1816 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001817 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001818 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1819 << D->getNameAsString()
1820 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001821 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001822 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001823 if (Verbose && POK == POK_VarAccess) {
1824 PartialDiagnosticAt VNote(D->getLocation(),
1825 S.PDiag(diag::note_guarded_by_declared_here)
1826 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001827 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001828 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001829 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001830 } else {
1831 switch (POK) {
1832 case POK_VarAccess:
1833 DiagID = diag::warn_variable_requires_lock;
1834 break;
1835 case POK_VarDereference:
1836 DiagID = diag::warn_var_deref_requires_lock;
1837 break;
1838 case POK_FunctionCall:
1839 DiagID = diag::warn_fun_requires_lock;
1840 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001841 case POK_PassByRef:
1842 DiagID = diag::warn_guarded_pass_by_reference;
1843 break;
1844 case POK_PtPassByRef:
1845 DiagID = diag::warn_pt_guarded_pass_by_reference;
1846 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001847 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001848 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1849 << D->getNameAsString()
1850 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001851 if (Verbose && POK == POK_VarAccess) {
1852 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001853 S.PDiag(diag::note_guarded_by_declared_here)
1854 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001855 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001856 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001857 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001858 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001859 }
1860
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001861 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1862 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001863 PartialDiagnosticAt Warning(Loc,
1864 S.PDiag(diag::warn_acquire_requires_negative_cap)
1865 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001866 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001867 }
1868
Aaron Ballmane0449042014-04-01 21:43:23 +00001869 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001870 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001871 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1872 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001873 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001874 }
1875
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001876 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1877 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001878 PartialDiagnosticAt Warning(Loc,
1879 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001880 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001881 }
1882
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001883 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001884 PartialDiagnosticAt Warning(Loc,
1885 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001886 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001887 }
1888
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001889 void enterFunction(const FunctionDecl* FD) override {
1890 CurrentFunction = FD;
1891 }
1892
1893 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001894 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001895 }
1896};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001897} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001898} // namespace threadSafety
1899} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001900
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001901//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001902// -Wconsumed
1903//===----------------------------------------------------------------------===//
1904
1905namespace clang {
1906namespace consumed {
1907namespace {
1908class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1909
1910 Sema &S;
1911 DiagList Warnings;
1912
1913public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001914
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001915 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001916
1917 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001918 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001919 for (const auto &Diag : Warnings) {
1920 S.Diag(Diag.first.first, Diag.first.second);
1921 for (const auto &Note : Diag.second)
1922 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001923 }
1924 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001925
1926 void warnLoopStateMismatch(SourceLocation Loc,
1927 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001928 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1929 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001930
1931 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001932 }
1933
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001934 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1935 StringRef VariableName,
1936 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001937 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001938
1939 PartialDiagnosticAt Warning(Loc, S.PDiag(
1940 diag::warn_param_return_typestate_mismatch) << VariableName <<
1941 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001942
1943 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001944 }
1945
DeLesley Hutchins69391772013-10-17 23:23:53 +00001946 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001947 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001948
1949 PartialDiagnosticAt Warning(Loc, S.PDiag(
1950 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001951
1952 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001953 }
1954
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001955 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001956 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001957 PartialDiagnosticAt Warning(Loc, S.PDiag(
1958 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001959
1960 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001961 }
1962
1963 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001964 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001965
1966 PartialDiagnosticAt Warning(Loc, S.PDiag(
1967 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001968
1969 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001970 }
1971
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001972 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001973 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001974
1975 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001976 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001977
1978 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001979 }
1980
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001981 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001982 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001983
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001984 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1985 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001986
1987 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001988 }
1989};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001990} // anonymous namespace
1991} // namespace consumed
1992} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001993
1994//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001995// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1996// warnings on a function, method, or block.
1997//===----------------------------------------------------------------------===//
1998
Ted Kremenek0b405322010-03-23 00:13:23 +00001999clang::sema::AnalysisBasedWarnings::Policy::Policy() {
2000 enableCheckFallThrough = 1;
2001 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002002 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002003 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00002004}
2005
Ted Kremenekad8753c2014-03-15 05:47:06 +00002006static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002007 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00002008}
2009
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002010clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2011 : S(s),
2012 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002013 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002014 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002015 MaxCFGBlocksPerFunction(0),
2016 NumUninitAnalysisFunctions(0),
2017 NumUninitAnalysisVariables(0),
2018 MaxUninitAnalysisVariablesPerFunction(0),
2019 NumUninitAnalysisBlockVisits(0),
2020 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00002021
2022 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00002023 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00002024
2025 DefaultPolicy.enableCheckUnreachable =
2026 isEnabled(D, warn_unreachable) ||
2027 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00002028 isEnabled(D, warn_unreachable_return) ||
2029 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00002030
2031 DefaultPolicy.enableThreadSafetyAnalysis =
2032 isEnabled(D, warn_double_lock);
2033
2034 DefaultPolicy.enableConsumedAnalysis =
2035 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00002036}
2037
Aaron Ballmane5195222014-05-15 20:50:47 +00002038static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2039 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00002040 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00002041}
2042
Ted Kremenek0b405322010-03-23 00:13:23 +00002043void clang::sema::
2044AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00002045 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00002046 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00002047
Ted Kremenek918fe842010-03-20 21:06:02 +00002048 // We avoid doing analysis-based warnings when there are errors for
2049 // two reasons:
2050 // (1) The CFGs often can't be constructed (if the body is invalid), so
2051 // don't bother trying.
2052 // (2) The code already has problems; running the analysis just takes more
2053 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00002054 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00002055
Olivier Goffart270ced22017-11-23 08:15:22 +00002056 // Do not do any analysis if we are going to just ignore them.
2057 if (Diags.getIgnoreAllWarnings() ||
2058 (Diags.getSuppressSystemWarnings() &&
2059 S.SourceMgr.isInSystemHeader(D->getLocation())))
Ted Kremenek0b405322010-03-23 00:13:23 +00002060 return;
2061
John McCall1d570a72010-08-25 05:56:39 +00002062 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00002063 if (cast<DeclContext>(D)->isDependentContext())
2064 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00002065
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002066 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002067 // Flush out any possibly unreachable diagnostics.
2068 flushDiagnostics(S, fscope);
2069 return;
2070 }
2071
Ted Kremenek918fe842010-03-20 21:06:02 +00002072 const Stmt *Body = D->getBody();
2073 assert(Body);
2074
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002075 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00002076 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00002077
Ted Kremenek918fe842010-03-20 21:06:02 +00002078 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00002079 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00002080 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2081 AC.getCFGBuildOptions().AddEHEdges = false;
2082 AC.getCFGBuildOptions().AddInitializers = true;
2083 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002084 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00002085 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00002086 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002087
Ted Kremenek9e100ea2011-07-19 14:18:48 +00002088 // Force that certain expressions appear as CFGElements in the CFG. This
2089 // is used to speed up various analyses.
2090 // FIXME: This isn't the right factoring. This is here for initial
2091 // prototyping, but we need a way for analyses to say what expressions they
2092 // expect to always be CFGElements and then fill in the BuildOptions
2093 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002094 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2095 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002096 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00002097 AC.getCFGBuildOptions().setAllAlwaysAdd();
2098 }
2099 else {
2100 AC.getCFGBuildOptions()
2101 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00002102 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00002103 .setAlwaysAdd(Stmt::BlockExprClass)
2104 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2105 .setAlwaysAdd(Stmt::DeclRefExprClass)
2106 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00002107 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2108 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00002109 }
Ted Kremenek918fe842010-03-20 21:06:02 +00002110
Richard Trieue9fa2662014-04-15 00:57:50 +00002111 // Install the logical handler for -Wtautological-overlap-compare
2112 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002113 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2114 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00002115 LEH.reset(new LogicalErrorHandler(S));
2116 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00002117 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002118
Ted Kremenek3427fac2011-02-23 01:52:04 +00002119 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00002120 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002121 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00002122
2123 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00002124 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2125 if (D.stmt)
2126 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00002127 }
2128
2129 if (AC.getCFG()) {
2130 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00002131 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00002132 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00002133 if (D.stmt) {
2134 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00002135 CFGReverseBlockReachabilityAnalysis *cra =
2136 AC.getCFGReachablityAnalysis();
2137 // FIXME: We should be able to assert that block is non-null, but
2138 // the CFG analysis can skip potentially-evaluated expressions in
2139 // edge cases; see test/Sema/vla-2.c.
2140 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002141 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00002142 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00002143 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00002144 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00002145 }
2146 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002147 if (!processed) {
2148 // Emit the warning anyway if we cannot map to a basic block.
2149 S.Diag(D.Loc, D.PD);
2150 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002151 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002152 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002153
2154 if (!analyzed)
2155 flushDiagnostics(S, fscope);
2156 }
2157
Ted Kremenek918fe842010-03-20 21:06:02 +00002158 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002159 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00002160 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002161 (isa<BlockDecl>(D)
2162 ? CheckFallThroughDiagnostics::MakeForBlock()
2163 : (isa<CXXMethodDecl>(D) &&
2164 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2165 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2166 ? CheckFallThroughDiagnostics::MakeForLambda()
Eric Fiselierda8f9b52017-05-25 02:16:53 +00002167 : (fscope->isCoroutine()
Eric Fiselier709d1b32016-10-27 07:30:31 +00002168 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2169 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Ted Kremenek1767a272011-02-23 01:51:48 +00002170 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00002171 }
2172
2173 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002174 if (P.enableCheckUnreachable) {
2175 // Only check for unreachable code on non-template instantiations.
2176 // Different template instantiations can effectively change the control-flow
2177 // and it is very difficult to prove that a snippet of code in a template
2178 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002179 bool isTemplateInstantiation = false;
2180 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2181 isTemplateInstantiation = Function->isTemplateInstantiation();
2182 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002183 CheckUnreachable(S, AC);
2184 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002185
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002186 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002187 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002188 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00002189 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002190 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002191 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002192 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002193 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2194 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002195
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002196 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2197 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002198 Reporter.emitDiagnostics();
2199 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002200
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002201 // Check for violations of consumed properties.
2202 if (P.enableConsumedAnalysis) {
2203 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002204 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002205 Analyzer.run(AC);
2206 }
2207
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002208 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2209 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2210 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002211 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002212 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002213 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002214 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002215 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002216 reporter, stats);
2217
2218 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2219 ++NumUninitAnalysisFunctions;
2220 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2221 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2222 MaxUninitAnalysisVariablesPerFunction =
2223 std::max(MaxUninitAnalysisVariablesPerFunction,
2224 stats.NumVariablesAnalyzed);
2225 MaxUninitAnalysisBlockVisitsPerFunction =
2226 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2227 stats.NumBlockVisits);
2228 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002229 }
2230 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002231
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002232 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002233 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2234 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2235 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Richard Smith4f902c72016-03-08 00:32:55 +00002236 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2237 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002238 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002239 }
2240
John McCall460ce582015-10-22 18:38:17 +00002241 if (S.getLangOpts().ObjCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002242 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002243 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002244
Richard Trieu2f024f42013-12-21 02:33:43 +00002245
2246 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002247 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2248 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002249 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2250 checkRecursiveFunction(S, FD, Body, AC);
2251 }
2252 }
2253
Erich Keane89fe9c22017-06-23 20:22:19 +00002254 // Check for throw out of non-throwing function.
2255 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2256 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2257 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2258 checkThrowInNonThrowingFunc(S, FD, AC);
2259
Richard Trieue9fa2662014-04-15 00:57:50 +00002260 // If none of the previous checks caused a CFG build, trigger one here
2261 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002262 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002263 D->getLocStart())) {
2264 AC.getCFG();
2265 }
2266
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002267 // Collect statistics about the CFG if it was built.
2268 if (S.CollectStats && AC.isCFGBuilt()) {
2269 ++NumFunctionsAnalyzed;
2270 if (CFG *cfg = AC.getCFG()) {
2271 // If we successfully built a CFG for this context, record some more
2272 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002273 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002274 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002275 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002276 } else {
2277 ++NumFunctionsWithBadCFGs;
2278 }
2279 }
2280}
2281
2282void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2283 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2284
2285 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2286 unsigned AvgCFGBlocksPerFunction =
2287 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2288 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2289 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2290 << " " << NumCFGBlocks << " CFG blocks built.\n"
2291 << " " << AvgCFGBlocksPerFunction
2292 << " average CFG blocks per function.\n"
2293 << " " << MaxCFGBlocksPerFunction
2294 << " max CFG blocks per function.\n";
2295
2296 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2297 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2298 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2299 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2300 llvm::errs() << NumUninitAnalysisFunctions
2301 << " functions analyzed for uninitialiazed variables\n"
2302 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2303 << " " << AvgUninitVariablesPerFunction
2304 << " average variables per function.\n"
2305 << " " << MaxUninitAnalysisVariablesPerFunction
2306 << " max variables per function.\n"
2307 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2308 << " " << AvgUninitBlockVisitsPerFunction
2309 << " average block visits per function.\n"
2310 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2311 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002312}