blob: f1b25753abff4d13cfd8654b64036a20551be32d [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"
Ted Kremenek918fe842010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#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"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
Alexander Kornienkoe61e5622012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenek918fe842010-03-20 21:06:02 +000055
56using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Unreachable code analysis.
60//===----------------------------------------------------------------------===//
61
62namespace {
63 class UnreachableCodeHandler : public reachable_code::Callback {
64 Sema &S;
65 public:
66 UnreachableCodeHandler(Sema &s) : S(s) {}
67
68 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
Ted Kremenek5b2c2102014-02-18 22:12:10 +000069 // As a heuristic prune all diagnostics not in the main file. Currently
70 // the majority of warnings in headers are false positives. These
71 // are largely caused by configuration state, e.g. preprocessor
72 // defined code, etc.
73 if (!S.getSourceManager().isInMainFile(L))
74 return;
Ted Kremenek918fe842010-03-20 21:06:02 +000075 S.Diag(L, diag::warn_unreachable) << R1 << R2;
76 }
77 };
78}
79
80/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +000081static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +000082 UnreachableCodeHandler UC(S);
83 reachable_code::FindUnreachableCode(AC, UC);
84}
85
86//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +000087// Check for infinite self-recursion in functions
88//===----------------------------------------------------------------------===//
89
90// All blocks are in one of three states. States are ordered so that blocks
91// can only move to higher states.
92enum RecursiveState {
93 FoundNoPath,
94 FoundPath,
95 FoundPathWithNoRecursiveCall
96};
97
98static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
99 CFGBlock &Block, unsigned ExitID,
100 llvm::SmallVectorImpl<RecursiveState> &States,
101 RecursiveState State) {
102 unsigned ID = Block.getBlockID();
103
104 // A block's state can only move to a higher state.
105 if (States[ID] >= State)
106 return;
107
108 States[ID] = State;
109
110 // Found a path to the exit node without a recursive call.
111 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
112 return;
113
114 if (State == FoundPathWithNoRecursiveCall) {
115 // If the current state is FoundPathWithNoRecursiveCall, the successors
116 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
117 // which, process all the Stmt's in this block to find any recursive calls.
118 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
119 if (I->getKind() != CFGElement::Statement)
120 continue;
121
122 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
123 if (CE && CE->getCalleeDecl() &&
124 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000125
126 // Skip function calls which are qualified with a templated class.
127 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
128 CE->getCallee()->IgnoreParenImpCasts())) {
129 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
130 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
131 isa<TemplateSpecializationType>(NNS->getAsType())) {
132 continue;
133 }
134 }
135 }
136
Richard Trieu2f024f42013-12-21 02:33:43 +0000137 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
138 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
139 !MCE->getMethodDecl()->isVirtual()) {
140 State = FoundPath;
141 break;
142 }
143 } else {
144 State = FoundPath;
145 break;
146 }
147 }
148 }
149 }
150
151 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
152 I != E; ++I)
153 if (*I)
154 checkForFunctionCall(S, FD, **I, ExitID, States, State);
155}
156
157static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
158 const Stmt *Body,
159 AnalysisDeclContext &AC) {
160 FD = FD->getCanonicalDecl();
161
162 // Only run on non-templated functions and non-templated members of
163 // templated classes.
164 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
165 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
166 return;
167
168 CFG *cfg = AC.getCFG();
169 if (cfg == 0) return;
170
171 // If the exit block is unreachable, skip processing the function.
172 if (cfg->getExit().pred_empty())
173 return;
174
175 // Mark all nodes as FoundNoPath, then begin processing the entry block.
176 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
177 FoundNoPath);
178 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
179 states, FoundPathWithNoRecursiveCall);
180
181 // Check that the exit block is reachable. This prevents triggering the
182 // warning on functions that do not terminate.
183 if (states[cfg->getExit().getBlockID()] == FoundPath)
184 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
185}
186
187//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000188// Check for missing return value.
189//===----------------------------------------------------------------------===//
190
John McCall5c6ec8c2010-05-16 09:34:11 +0000191enum ControlFlowKind {
192 UnknownFallThrough,
193 NeverFallThrough,
194 MaybeFallThrough,
195 AlwaysFallThrough,
196 NeverFallThroughOrReturn
197};
Ted Kremenek918fe842010-03-20 21:06:02 +0000198
199/// CheckFallThrough - Check that we don't fall off the end of a
200/// Statement that should return a value.
201///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000202/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
203/// MaybeFallThrough iff we might or might not fall off the end,
204/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
205/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000206/// statement but we may return. We assume that functions not marked noreturn
207/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000208static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000209 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000210 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000211
212 // The CFG leaves in dead things, and we don't want the dead code paths to
213 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000214 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000215 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000216 live);
217
218 bool AddEHEdges = AC.getAddEHEdges();
219 if (!AddEHEdges && count != cfg->getNumBlockIDs())
220 // When there are things remaining dead, and we didn't add EH edges
221 // from CallExprs to the catch clauses, we have to go back and
222 // mark them as live.
223 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
224 CFGBlock &b = **I;
225 if (!live[b.getBlockID()]) {
226 if (b.pred_begin() == b.pred_end()) {
227 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
228 // When not adding EH edges from calls, catch clauses
229 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000230 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000231 continue;
232 }
233 }
234 }
235
236 // Now we know what is live, we check the live precessors of the exit block
237 // and look for fall through paths, being careful to ignore normal returns,
238 // and exceptional paths.
239 bool HasLiveReturn = false;
240 bool HasFakeEdge = false;
241 bool HasPlainEdge = false;
242 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000243
244 // Ignore default cases that aren't likely to be reachable because all
245 // enums in a switch(X) have explicit case statements.
246 CFGBlock::FilterOptions FO;
247 FO.IgnoreDefaultsWithCoveredEnums = 1;
248
249 for (CFGBlock::filtered_pred_iterator
250 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
251 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000252 if (!live[B.getBlockID()])
253 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000254
Chandler Carruth03faf782011-09-13 09:53:58 +0000255 // Skip blocks which contain an element marked as no-return. They don't
256 // represent actually viable edges into the exit block, so mark them as
257 // abnormal.
258 if (B.hasNoReturnElement()) {
259 HasAbnormalEdge = true;
260 continue;
261 }
262
Ted Kremenek5d068492011-01-26 04:49:52 +0000263 // Destructors can appear after the 'return' in the CFG. This is
264 // normal. We need to look pass the destructors for the return
265 // statement (if it exists).
266 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000267
Chandler Carruth03faf782011-09-13 09:53:58 +0000268 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000269 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000270 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000271
Ted Kremenek5d068492011-01-26 04:49:52 +0000272 // No more CFGElements in the block?
273 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000274 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
275 HasAbnormalEdge = true;
276 continue;
277 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000278 // A labeled empty statement, or the entry block...
279 HasPlainEdge = true;
280 continue;
281 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000282
David Blaikie2a01f5d2013-02-21 20:58:29 +0000283 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000284 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000285 if (isa<ReturnStmt>(S)) {
286 HasLiveReturn = true;
287 continue;
288 }
289 if (isa<ObjCAtThrowStmt>(S)) {
290 HasFakeEdge = true;
291 continue;
292 }
293 if (isa<CXXThrowExpr>(S)) {
294 HasFakeEdge = true;
295 continue;
296 }
Chad Rosier32503022012-06-11 20:47:18 +0000297 if (isa<MSAsmStmt>(S)) {
298 // TODO: Verify this is correct.
299 HasFakeEdge = true;
300 HasLiveReturn = true;
301 continue;
302 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000303 if (isa<CXXTryStmt>(S)) {
304 HasAbnormalEdge = true;
305 continue;
306 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000307 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
308 == B.succ_end()) {
309 HasAbnormalEdge = true;
310 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000311 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000312
313 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000314 }
315 if (!HasPlainEdge) {
316 if (HasLiveReturn)
317 return NeverFallThrough;
318 return NeverFallThroughOrReturn;
319 }
320 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
321 return MaybeFallThrough;
322 // This says AlwaysFallThrough for calls to functions that are not marked
323 // noreturn, that don't return. If people would like this warning to be more
324 // accurate, such functions should be marked as noreturn.
325 return AlwaysFallThrough;
326}
327
Dan Gohman28ade552010-07-26 21:25:24 +0000328namespace {
329
Ted Kremenek918fe842010-03-20 21:06:02 +0000330struct CheckFallThroughDiagnostics {
331 unsigned diag_MaybeFallThrough_HasNoReturn;
332 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
333 unsigned diag_AlwaysFallThrough_HasNoReturn;
334 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
335 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000336 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000337 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000338
Douglas Gregor24f27692010-04-16 23:28:44 +0000339 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000340 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000341 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000342 D.diag_MaybeFallThrough_HasNoReturn =
343 diag::warn_falloff_noreturn_function;
344 D.diag_MaybeFallThrough_ReturnsNonVoid =
345 diag::warn_maybe_falloff_nonvoid_function;
346 D.diag_AlwaysFallThrough_HasNoReturn =
347 diag::warn_falloff_noreturn_function;
348 D.diag_AlwaysFallThrough_ReturnsNonVoid =
349 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000350
351 // Don't suggest that virtual functions be marked "noreturn", since they
352 // might be overridden by non-noreturn functions.
353 bool isVirtualMethod = false;
354 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
355 isVirtualMethod = Method->isVirtual();
356
Douglas Gregor0de57202011-10-10 18:15:57 +0000357 // Don't suggest that template instantiations be marked "noreturn"
358 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000359 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
360 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000361
362 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000363 D.diag_NeverFallThroughOrReturn =
364 diag::warn_suggest_noreturn_function;
365 else
366 D.diag_NeverFallThroughOrReturn = 0;
367
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000368 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000369 return D;
370 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000371
Ted Kremenek918fe842010-03-20 21:06:02 +0000372 static CheckFallThroughDiagnostics MakeForBlock() {
373 CheckFallThroughDiagnostics D;
374 D.diag_MaybeFallThrough_HasNoReturn =
375 diag::err_noreturn_block_has_return_expr;
376 D.diag_MaybeFallThrough_ReturnsNonVoid =
377 diag::err_maybe_falloff_nonvoid_block;
378 D.diag_AlwaysFallThrough_HasNoReturn =
379 diag::err_noreturn_block_has_return_expr;
380 D.diag_AlwaysFallThrough_ReturnsNonVoid =
381 diag::err_falloff_nonvoid_block;
382 D.diag_NeverFallThroughOrReturn =
383 diag::warn_suggest_noreturn_block;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000384 D.funMode = Block;
385 return D;
386 }
387
388 static CheckFallThroughDiagnostics MakeForLambda() {
389 CheckFallThroughDiagnostics D;
390 D.diag_MaybeFallThrough_HasNoReturn =
391 diag::err_noreturn_lambda_has_return_expr;
392 D.diag_MaybeFallThrough_ReturnsNonVoid =
393 diag::warn_maybe_falloff_nonvoid_lambda;
394 D.diag_AlwaysFallThrough_HasNoReturn =
395 diag::err_noreturn_lambda_has_return_expr;
396 D.diag_AlwaysFallThrough_ReturnsNonVoid =
397 diag::warn_falloff_nonvoid_lambda;
398 D.diag_NeverFallThroughOrReturn = 0;
399 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000400 return D;
401 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000402
David Blaikie9c902b52011-09-25 23:23:43 +0000403 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000404 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000405 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000406 return (ReturnsVoid ||
407 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000408 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000409 && (!HasNoReturn ||
410 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000411 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000412 && (!ReturnsVoid ||
413 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000414 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000415 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000416
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000417 // For blocks / lambdas.
418 return ReturnsVoid && !HasNoReturn
419 && ((funMode == Lambda) ||
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000420 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000421 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000422 }
423};
424
Dan Gohman28ade552010-07-26 21:25:24 +0000425}
426
Ted Kremenek918fe842010-03-20 21:06:02 +0000427/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
428/// function that should return a value. Check that we don't fall off the end
429/// of a noreturn function. We assume that functions and blocks not marked
430/// noreturn will return.
431static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000432 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000433 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000434 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000435
436 bool ReturnsVoid = false;
437 bool HasNoReturn = false;
438
439 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000440 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000441 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000442 }
443 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000444 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000445 HasNoReturn = MD->hasAttr<NoReturnAttr>();
446 }
447 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000448 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000449 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000450 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000451 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000452 ReturnsVoid = true;
453 if (FT->getNoReturnAttr())
454 HasNoReturn = true;
455 }
456 }
457
David Blaikie9c902b52011-09-25 23:23:43 +0000458 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000459
460 // Short circuit for compilation speed.
461 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
462 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000463
Ted Kremenek918fe842010-03-20 21:06:02 +0000464 // FIXME: Function try block
465 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
466 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000467 case UnknownFallThrough:
468 break;
469
Ted Kremenek918fe842010-03-20 21:06:02 +0000470 case MaybeFallThrough:
471 if (HasNoReturn)
472 S.Diag(Compound->getRBracLoc(),
473 CD.diag_MaybeFallThrough_HasNoReturn);
474 else if (!ReturnsVoid)
475 S.Diag(Compound->getRBracLoc(),
476 CD.diag_MaybeFallThrough_ReturnsNonVoid);
477 break;
478 case AlwaysFallThrough:
479 if (HasNoReturn)
480 S.Diag(Compound->getRBracLoc(),
481 CD.diag_AlwaysFallThrough_HasNoReturn);
482 else if (!ReturnsVoid)
483 S.Diag(Compound->getRBracLoc(),
484 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
485 break;
486 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000487 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
488 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
489 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000490 << 0 << FD;
491 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
492 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
493 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000494 } else {
495 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
496 }
497 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000498 break;
499 case NeverFallThrough:
500 break;
501 }
502 }
503}
504
505//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000506// -Wuninitialized
507//===----------------------------------------------------------------------===//
508
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000509namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000510/// ContainsReference - A visitor class to search for references to
511/// a particular declaration (the needle) within any evaluated component of an
512/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000513class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000514 bool FoundReference;
515 const DeclRefExpr *Needle;
516
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000517public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000518 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
519 : EvaluatedExprVisitor<ContainsReference>(Context),
520 FoundReference(false), Needle(Needle) {}
521
522 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000523 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000524 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000525 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000526
527 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000528 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000529
530 void VisitDeclRefExpr(DeclRefExpr *E) {
531 if (E == Needle)
532 FoundReference = true;
533 else
534 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000535 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000536
537 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000538};
539}
540
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000541static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000542 QualType VariableTy = VD->getType().getCanonicalType();
543 if (VariableTy->isBlockPointerType() &&
544 !VD->hasAttr<BlocksAttr>()) {
545 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
546 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
547 return true;
548 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000549
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000550 // Don't issue a fixit if there is already an initializer.
551 if (VD->getInit())
552 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000553
554 // Don't suggest a fixit inside macros.
555 if (VD->getLocEnd().isMacroID())
556 return false;
557
Richard Smith8d06f422012-01-12 23:53:29 +0000558 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000559
560 // Suggest possible initialization (if any).
561 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
562 if (Init.empty())
563 return false;
564
Richard Smith8d06f422012-01-12 23:53:29 +0000565 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
566 << FixItHint::CreateInsertion(Loc, Init);
567 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000568}
569
Richard Smith1bb8edb82012-05-26 06:20:46 +0000570/// Create a fixit to remove an if-like statement, on the assumption that its
571/// condition is CondVal.
572static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
573 const Stmt *Else, bool CondVal,
574 FixItHint &Fixit1, FixItHint &Fixit2) {
575 if (CondVal) {
576 // If condition is always true, remove all but the 'then'.
577 Fixit1 = FixItHint::CreateRemoval(
578 CharSourceRange::getCharRange(If->getLocStart(),
579 Then->getLocStart()));
580 if (Else) {
581 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
582 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
583 Fixit2 = FixItHint::CreateRemoval(
584 SourceRange(ElseKwLoc, Else->getLocEnd()));
585 }
586 } else {
587 // If condition is always false, remove all but the 'else'.
588 if (Else)
589 Fixit1 = FixItHint::CreateRemoval(
590 CharSourceRange::getCharRange(If->getLocStart(),
591 Else->getLocStart()));
592 else
593 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
594 }
595}
596
597/// DiagUninitUse -- Helper function to produce a diagnostic for an
598/// uninitialized use of a variable.
599static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
600 bool IsCapturedByBlock) {
601 bool Diagnosed = false;
602
Richard Smithba8071e2013-09-12 18:49:10 +0000603 switch (Use.getKind()) {
604 case UninitUse::Always:
605 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
606 << VD->getDeclName() << IsCapturedByBlock
607 << Use.getUser()->getSourceRange();
608 return;
609
610 case UninitUse::AfterDecl:
611 case UninitUse::AfterCall:
612 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
613 << VD->getDeclName() << IsCapturedByBlock
614 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
615 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
616 << VD->getSourceRange();
617 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
618 << IsCapturedByBlock << Use.getUser()->getSourceRange();
619 return;
620
621 case UninitUse::Maybe:
622 case UninitUse::Sometimes:
623 // Carry on to report sometimes-uninitialized branches, if possible,
624 // or a 'may be used uninitialized' diagnostic otherwise.
625 break;
626 }
627
Richard Smith1bb8edb82012-05-26 06:20:46 +0000628 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000629 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
630 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000631 assert(Use.getKind() == UninitUse::Sometimes);
632
633 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000634 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000635
636 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000637 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000638 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000639 SourceRange Range;
640
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000641 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000642 // For all binary terminators, branch 0 is taken if the condition is true,
643 // and branch 1 is taken if the condition is false.
644 int RemoveDiagKind = -1;
645 const char *FixitStr =
646 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
647 : (I->Output ? "1" : "0");
648 FixItHint Fixit1, Fixit2;
649
Richard Smithba8071e2013-09-12 18:49:10 +0000650 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000651 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000652 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000653 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000654 continue;
655
656 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000657 case Stmt::IfStmtClass: {
658 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000659 DiagKind = 0;
660 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000661 Range = IS->getCond()->getSourceRange();
662 RemoveDiagKind = 0;
663 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
664 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000665 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000666 }
667 case Stmt::ConditionalOperatorClass: {
668 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000669 DiagKind = 0;
670 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000671 Range = CO->getCond()->getSourceRange();
672 RemoveDiagKind = 0;
673 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
674 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000675 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000676 }
Richard Smith4323bf82012-05-25 02:17:09 +0000677 case Stmt::BinaryOperatorClass: {
678 const BinaryOperator *BO = cast<BinaryOperator>(Term);
679 if (!BO->isLogicalOp())
680 continue;
681 DiagKind = 0;
682 Str = BO->getOpcodeStr();
683 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000684 RemoveDiagKind = 0;
685 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
686 (BO->getOpcode() == BO_LOr && !I->Output))
687 // true && y -> y, false || y -> y.
688 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
689 BO->getOperatorLoc()));
690 else
691 // false && y -> false, true || y -> true.
692 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000693 break;
694 }
695
696 // "loop is entered / loop is exited".
697 case Stmt::WhileStmtClass:
698 DiagKind = 1;
699 Str = "while";
700 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000701 RemoveDiagKind = 1;
702 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000703 break;
704 case Stmt::ForStmtClass:
705 DiagKind = 1;
706 Str = "for";
707 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000708 RemoveDiagKind = 1;
709 if (I->Output)
710 Fixit1 = FixItHint::CreateRemoval(Range);
711 else
712 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000713 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000714 case Stmt::CXXForRangeStmtClass:
715 if (I->Output == 1) {
716 // The use occurs if a range-based for loop's body never executes.
717 // That may be impossible, and there's no syntactic fix for this,
718 // so treat it as a 'may be uninitialized' case.
719 continue;
720 }
721 DiagKind = 1;
722 Str = "for";
723 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
724 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000725
726 // "condition is true / loop is exited".
727 case Stmt::DoStmtClass:
728 DiagKind = 2;
729 Str = "do";
730 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000731 RemoveDiagKind = 1;
732 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000733 break;
734
735 // "switch case is taken".
736 case Stmt::CaseStmtClass:
737 DiagKind = 3;
738 Str = "case";
739 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
740 break;
741 case Stmt::DefaultStmtClass:
742 DiagKind = 3;
743 Str = "default";
744 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
745 break;
746 }
747
Richard Smith1bb8edb82012-05-26 06:20:46 +0000748 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
749 << VD->getDeclName() << IsCapturedByBlock << DiagKind
750 << Str << I->Output << Range;
751 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
752 << IsCapturedByBlock << User->getSourceRange();
753 if (RemoveDiagKind != -1)
754 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
755 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
756
757 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000758 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000759
760 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000761 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000762 << VD->getDeclName() << IsCapturedByBlock
763 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000764}
765
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000766/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
767/// uninitialized variable. This manages the different forms of diagnostic
768/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000769/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000770/// false.
771static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000772 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000773 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000774
Richard Smith4323bf82012-05-25 02:17:09 +0000775 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000776 // Inspect the initializer of the variable declaration which is
777 // being referenced prior to its initialization. We emit
778 // specialized diagnostics for self-initialization, and we
779 // specifically avoid warning about self references which take the
780 // form of:
781 //
782 // int x = x;
783 //
784 // This is used to indicate to GCC that 'x' is intentionally left
785 // uninitialized. Proven code paths which access 'x' in
786 // an uninitialized state after this will still warn.
787 if (const Expr *Initializer = VD->getInit()) {
788 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
789 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000790
Richard Trieu43a2fc72012-05-09 21:08:22 +0000791 ContainsReference CR(S.Context, DRE);
792 CR.Visit(const_cast<Expr*>(Initializer));
793 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000794 S.Diag(DRE->getLocStart(),
795 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000796 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
797 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000798 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000799 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000800
Richard Smith1bb8edb82012-05-26 06:20:46 +0000801 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000802 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000803 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000804 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
805 S.Diag(BE->getLocStart(),
806 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000807 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000808 else
809 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000810 }
811
812 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000813 // the initializer of that declaration & we didn't already suggest
814 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000815 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000816 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
817 << VD->getDeclName();
818
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000819 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000820}
821
Richard Smith84837d52012-05-03 18:27:39 +0000822namespace {
823 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
824 public:
825 FallthroughMapper(Sema &S)
826 : FoundSwitchStatements(false),
827 S(S) {
828 }
829
830 bool foundSwitchStatements() const { return FoundSwitchStatements; }
831
832 void markFallthroughVisited(const AttributedStmt *Stmt) {
833 bool Found = FallthroughStmts.erase(Stmt);
834 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000835 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000836 }
837
838 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
839
840 const AttrStmts &getFallthroughStmts() const {
841 return FallthroughStmts;
842 }
843
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000844 void fillReachableBlocks(CFG *Cfg) {
845 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
846 std::deque<const CFGBlock *> BlockQueue;
847
848 ReachableBlocks.insert(&Cfg->getEntry());
849 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000850 // Mark all case blocks reachable to avoid problems with switching on
851 // constants, covered enums, etc.
852 // These blocks can contain fall-through annotations, and we don't want to
853 // issue a warn_fallthrough_attr_unreachable for them.
854 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
855 const CFGBlock *B = *I;
856 const Stmt *L = B->getLabel();
857 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
858 BlockQueue.push_back(B);
859 }
860
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000861 while (!BlockQueue.empty()) {
862 const CFGBlock *P = BlockQueue.front();
863 BlockQueue.pop_front();
864 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
865 E = P->succ_end();
866 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000867 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000868 BlockQueue.push_back(*I);
869 }
870 }
871 }
872
Richard Smith84837d52012-05-03 18:27:39 +0000873 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000874 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
875
Richard Smith84837d52012-05-03 18:27:39 +0000876 int UnannotatedCnt = 0;
877 AnnotatedCnt = 0;
878
879 std::deque<const CFGBlock*> BlockQueue;
880
881 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
882
883 while (!BlockQueue.empty()) {
884 const CFGBlock *P = BlockQueue.front();
885 BlockQueue.pop_front();
886
887 const Stmt *Term = P->getTerminator();
888 if (Term && isa<SwitchStmt>(Term))
889 continue; // Switch statement, good.
890
891 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
892 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
893 continue; // Previous case label has no statements, good.
894
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000895 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
896 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
897 continue; // Case label is preceded with a normal label, good.
898
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000899 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000900 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
901 ElemEnd = P->rend();
902 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000903 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
904 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000905 S.Diag(AS->getLocStart(),
906 diag::warn_fallthrough_attr_unreachable);
907 markFallthroughVisited(AS);
908 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000909 break;
Richard Smith84837d52012-05-03 18:27:39 +0000910 }
911 // Don't care about other unreachable statements.
912 }
913 }
914 // If there are no unreachable statements, this may be a special
915 // case in CFG:
916 // case X: {
917 // A a; // A has a destructor.
918 // break;
919 // }
920 // // <<<< This place is represented by a 'hanging' CFG block.
921 // case Y:
922 continue;
923 }
924
925 const Stmt *LastStmt = getLastStmt(*P);
926 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
927 markFallthroughVisited(AS);
928 ++AnnotatedCnt;
929 continue; // Fallthrough annotation, good.
930 }
931
932 if (!LastStmt) { // This block contains no executable statements.
933 // Traverse its predecessors.
934 std::copy(P->pred_begin(), P->pred_end(),
935 std::back_inserter(BlockQueue));
936 continue;
937 }
938
939 ++UnannotatedCnt;
940 }
941 return !!UnannotatedCnt;
942 }
943
944 // RecursiveASTVisitor setup.
945 bool shouldWalkTypesOfTypeLocs() const { return false; }
946
947 bool VisitAttributedStmt(AttributedStmt *S) {
948 if (asFallThroughAttr(S))
949 FallthroughStmts.insert(S);
950 return true;
951 }
952
953 bool VisitSwitchStmt(SwitchStmt *S) {
954 FoundSwitchStatements = true;
955 return true;
956 }
957
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000958 // We don't want to traverse local type declarations. We analyze their
959 // methods separately.
960 bool TraverseDecl(Decl *D) { return true; }
961
Richard Smith84837d52012-05-03 18:27:39 +0000962 private:
963
964 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
965 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
966 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
967 return AS;
968 }
969 return 0;
970 }
971
972 static const Stmt *getLastStmt(const CFGBlock &B) {
973 if (const Stmt *Term = B.getTerminator())
974 return Term;
975 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
976 ElemEnd = B.rend();
977 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000978 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
979 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +0000980 }
981 // Workaround to detect a statement thrown out by CFGBuilder:
982 // case X: {} case Y:
983 // case X: ; case Y:
984 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
985 if (!isa<SwitchCase>(SW->getSubStmt()))
986 return SW->getSubStmt();
987
988 return 0;
989 }
990
991 bool FoundSwitchStatements;
992 AttrStmts FallthroughStmts;
993 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000994 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +0000995 };
996}
997
Alexander Kornienko06caf7d2012-06-02 01:01:07 +0000998static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +0000999 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001000 // Only perform this analysis when using C++11. There is no good workflow
1001 // for this warning when not using C++11. There is no good way to silence
1002 // the warning (no attribute is available) unless we are using C++11's support
1003 // for generalized attributes. Once could use pragmas to silence the warning,
1004 // but as a general solution that is gross and not in the spirit of this
1005 // warning.
1006 //
1007 // NOTE: This an intermediate solution. There are on-going discussions on
1008 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001009 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001010 return;
1011
Richard Smith84837d52012-05-03 18:27:39 +00001012 FallthroughMapper FM(S);
1013 FM.TraverseStmt(AC.getBody());
1014
1015 if (!FM.foundSwitchStatements())
1016 return;
1017
Alexis Hunt2178f142012-06-15 21:22:05 +00001018 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001019 return;
1020
Richard Smith84837d52012-05-03 18:27:39 +00001021 CFG *Cfg = AC.getCFG();
1022
1023 if (!Cfg)
1024 return;
1025
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001026 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001027
1028 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001029 const CFGBlock *B = *I;
1030 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001031
1032 if (!Label || !isa<SwitchCase>(Label))
1033 continue;
1034
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001035 int AnnotatedCnt;
1036
Alexander Kornienko55488792013-01-25 15:49:34 +00001037 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001038 continue;
1039
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001040 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001041 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1042 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001043
1044 if (!AnnotatedCnt) {
1045 SourceLocation L = Label->getLocStart();
1046 if (L.isMacroID())
1047 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001048 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001049 const Stmt *Term = B->getTerminator();
1050 // Skip empty cases.
1051 while (B->empty() && !Term && B->succ_size() == 1) {
1052 B = *B->succ_begin();
1053 Term = B->getTerminator();
1054 }
1055 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001056 Preprocessor &PP = S.getPreprocessor();
1057 TokenValue Tokens[] = {
1058 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1059 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1060 tok::r_square, tok::r_square
1061 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001062 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1063 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1064 if (!MacroName.empty())
1065 AnnotationSpelling = MacroName;
1066 SmallString<64> TextToInsert(AnnotationSpelling);
1067 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001068 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001069 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001070 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001071 }
Richard Smith84837d52012-05-03 18:27:39 +00001072 }
1073 S.Diag(L, diag::note_insert_break_fixit) <<
1074 FixItHint::CreateInsertion(L, "break; ");
1075 }
1076 }
1077
1078 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1079 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1080 E = Fallthroughs.end();
1081 I != E; ++I) {
1082 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1083 }
1084
1085}
1086
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001087namespace {
Jordan Rosed61f3b42012-09-28 22:29:02 +00001088typedef std::pair<const Stmt *,
1089 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
1090 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001091
Jordan Rosed61f3b42012-09-28 22:29:02 +00001092class StmtUseSorter {
Jordan Rosed3934582012-09-28 22:21:30 +00001093 const SourceManager &SM;
1094
1095public:
Jordan Rosed61f3b42012-09-28 22:29:02 +00001096 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
Jordan Rosed3934582012-09-28 22:21:30 +00001097
1098 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1099 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1100 RHS.first->getLocStart());
1101 }
1102};
Jordan Rosed61f3b42012-09-28 22:29:02 +00001103}
Jordan Rosed3934582012-09-28 22:21:30 +00001104
Jordan Rose25c0ea82012-10-29 17:46:47 +00001105static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1106 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001107 assert(S);
1108
1109 do {
1110 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001111 case Stmt::ForStmtClass:
1112 case Stmt::WhileStmtClass:
1113 case Stmt::CXXForRangeStmtClass:
1114 case Stmt::ObjCForCollectionStmtClass:
1115 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001116 case Stmt::DoStmtClass: {
1117 const Expr *Cond = cast<DoStmt>(S)->getCond();
1118 llvm::APSInt Val;
1119 if (!Cond->EvaluateAsInt(Val, Ctx))
1120 return true;
1121 return Val.getBoolValue();
1122 }
Jordan Rose76831c62012-10-11 16:10:19 +00001123 default:
1124 break;
1125 }
1126 } while ((S = PM.getParent(S)));
1127
1128 return false;
1129}
1130
Jordan Rosed3934582012-09-28 22:21:30 +00001131
1132static void diagnoseRepeatedUseOfWeak(Sema &S,
1133 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001134 const Decl *D,
1135 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001136 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1137 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1138 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1139
Jordan Rose25c0ea82012-10-29 17:46:47 +00001140 ASTContext &Ctx = S.getASTContext();
1141
Jordan Rosed3934582012-09-28 22:21:30 +00001142 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1143
1144 // Extract all weak objects that are referenced more than once.
1145 SmallVector<StmtUsesPair, 8> UsesByStmt;
1146 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1147 I != E; ++I) {
1148 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001149
1150 // Find the first read of the weak object.
1151 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1152 for ( ; UI != UE; ++UI) {
1153 if (UI->isUnsafe())
1154 break;
1155 }
1156
1157 // If there were only writes to this object, don't warn.
1158 if (UI == UE)
1159 continue;
1160
Jordan Rose76831c62012-10-11 16:10:19 +00001161 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001162 // read is not within a loop, don't warn. Additionally, don't warn in a
1163 // loop if the base object is a local variable -- local variables are often
1164 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001165 if (UI == Uses.begin()) {
1166 WeakUseVector::const_iterator UI2 = UI;
1167 for (++UI2; UI2 != UE; ++UI2)
1168 if (UI2->isUnsafe())
1169 break;
1170
Jordan Rose25c0ea82012-10-29 17:46:47 +00001171 if (UI2 == UE) {
1172 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001173 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001174
1175 const WeakObjectProfileTy &Profile = I->first;
1176 if (!Profile.isExactProfile())
1177 continue;
1178
1179 const NamedDecl *Base = Profile.getBase();
1180 if (!Base)
1181 Base = Profile.getProperty();
1182 assert(Base && "A profile always has a base or property.");
1183
1184 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1185 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1186 continue;
1187 }
Jordan Rose76831c62012-10-11 16:10:19 +00001188 }
1189
Jordan Rosed3934582012-09-28 22:21:30 +00001190 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1191 }
1192
1193 if (UsesByStmt.empty())
1194 return;
1195
1196 // Sort by first use so that we emit the warnings in a deterministic order.
1197 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Jordan Rosed61f3b42012-09-28 22:29:02 +00001198 StmtUseSorter(S.getSourceManager()));
Jordan Rosed3934582012-09-28 22:21:30 +00001199
1200 // Classify the current code body for better warning text.
1201 // This enum should stay in sync with the cases in
1202 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1203 // FIXME: Should we use a common classification enum and the same set of
1204 // possibilities all throughout Sema?
1205 enum {
1206 Function,
1207 Method,
1208 Block,
1209 Lambda
1210 } FunctionKind;
1211
1212 if (isa<sema::BlockScopeInfo>(CurFn))
1213 FunctionKind = Block;
1214 else if (isa<sema::LambdaScopeInfo>(CurFn))
1215 FunctionKind = Lambda;
1216 else if (isa<ObjCMethodDecl>(D))
1217 FunctionKind = Method;
1218 else
1219 FunctionKind = Function;
1220
1221 // Iterate through the sorted problems and emit warnings for each.
1222 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1223 E = UsesByStmt.end();
1224 I != E; ++I) {
1225 const Stmt *FirstRead = I->first;
1226 const WeakObjectProfileTy &Key = I->second->first;
1227 const WeakUseVector &Uses = I->second->second;
1228
Jordan Rose657b5f42012-09-28 22:21:35 +00001229 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1230 // may not contain enough information to determine that these are different
1231 // properties. We can only be 100% sure of a repeated use in certain cases,
1232 // and we adjust the diagnostic kind accordingly so that the less certain
1233 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001234 unsigned DiagKind;
1235 if (Key.isExactProfile())
1236 DiagKind = diag::warn_arc_repeated_use_of_weak;
1237 else
1238 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1239
Jordan Rose657b5f42012-09-28 22:21:35 +00001240 // Classify the weak object being accessed for better warning text.
1241 // This enum should stay in sync with the cases in
1242 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1243 enum {
1244 Variable,
1245 Property,
1246 ImplicitProperty,
1247 Ivar
1248 } ObjectKind;
1249
1250 const NamedDecl *D = Key.getProperty();
1251 if (isa<VarDecl>(D))
1252 ObjectKind = Variable;
1253 else if (isa<ObjCPropertyDecl>(D))
1254 ObjectKind = Property;
1255 else if (isa<ObjCMethodDecl>(D))
1256 ObjectKind = ImplicitProperty;
1257 else if (isa<ObjCIvarDecl>(D))
1258 ObjectKind = Ivar;
1259 else
1260 llvm_unreachable("Unexpected weak object kind!");
1261
Jordan Rosed3934582012-09-28 22:21:30 +00001262 // Show the first time the object was read.
1263 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001264 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001265 << FirstRead->getSourceRange();
1266
1267 // Print all the other accesses as notes.
1268 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1269 UI != UE; ++UI) {
1270 if (UI->getUseExpr() == FirstRead)
1271 continue;
1272 S.Diag(UI->getUseExpr()->getLocStart(),
1273 diag::note_arc_weak_also_accessed_here)
1274 << UI->getUseExpr()->getSourceRange();
1275 }
1276 }
1277}
1278
1279
1280namespace {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001281struct SLocSort {
Ted Kremenekc8c4e5f2011-03-15 04:57:38 +00001282 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith4323bf82012-05-25 02:17:09 +00001283 // Prefer a more confident report over a less confident one.
1284 if (a.getKind() != b.getKind())
1285 return a.getKind() > b.getKind();
1286 SourceLocation aLoc = a.getUser()->getLocStart();
1287 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek39fa0562011-01-21 19:41:41 +00001288 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1289 }
1290};
1291
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001292class UninitValsDiagReporter : public UninitVariablesHandler {
1293 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001294 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001295 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001296 // Prefer using MapVector to DenseMap, so that iteration order will be
1297 // the same as insertion order. This is needed to obtain a deterministic
1298 // order of diagnostics when calling flushDiagnostics().
1299 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001300 UsesMap *uses;
1301
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001302public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001303 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1304 ~UninitValsDiagReporter() {
1305 flushDiagnostics();
1306 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001307
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001308 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001309 if (!uses)
1310 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001311
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001312 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001313 if (!V.getPointer())
1314 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001315
Ted Kremenek596fa162011-10-13 18:50:06 +00001316 return V;
1317 }
1318
Richard Smith4323bf82012-05-25 02:17:09 +00001319 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001320 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001321 }
1322
1323 void handleSelfInit(const VarDecl *vd) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001324 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001325 }
1326
1327 void flushDiagnostics() {
1328 if (!uses)
1329 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001330
Ted Kremenek39fa0562011-01-21 19:41:41 +00001331 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1332 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001333 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001334
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001335 UsesVec *vec = V.getPointer();
1336 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001337
1338 // Specially handle the case where we have uses of an uninitialized
1339 // variable, but the root cause is an idiomatic self-init. We want
1340 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001341 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001342 DiagnoseUninitializedUse(S, vd,
1343 UninitUse(vd->getInit()->IgnoreParenCasts(),
1344 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001345 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001346 else {
1347 // Sort the uses by their SourceLocations. While not strictly
1348 // guaranteed to produce them in line/column order, this will provide
1349 // a stable ordering.
1350 std::sort(vec->begin(), vec->end(), SLocSort());
1351
1352 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1353 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001354 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1355 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1356
1357 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001358 // Skip further diagnostics for this variable. We try to warn only
1359 // on the first point at which a variable is used uninitialized.
1360 break;
1361 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001362 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001363
1364 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001365 delete vec;
1366 }
1367 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001368 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001369
1370private:
1371 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1372 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001373 if (i->getKind() == UninitUse::Always ||
1374 i->getKind() == UninitUse::AfterCall ||
1375 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001376 return true;
1377 }
1378 }
1379 return false;
1380}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001381};
1382}
1383
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001384namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001385namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001386typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001387typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001388typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001389
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001390struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001391 SourceManager &SM;
1392 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001393
1394 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1395 // Although this call will be slow, this is only called when outputting
1396 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001397 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001398 }
1399};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001400}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001401
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001402//===----------------------------------------------------------------------===//
1403// -Wthread-safety
1404//===----------------------------------------------------------------------===//
1405namespace clang {
1406namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001407namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001408class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1409 Sema &S;
1410 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001411 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001412
1413 // Helper functions
1414 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001415 // Gracefully handle rare cases when the analysis can't get a more
1416 // precise source location.
1417 if (!Loc.isValid())
1418 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001419 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1420 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001421 }
1422
1423 public:
Richard Smith92286672012-02-03 04:45:26 +00001424 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1425 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001426
1427 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1428 /// We need to output diagnostics produced while iterating through
1429 /// the lockset in deterministic order, so this function orders diagnostics
1430 /// and outputs them.
1431 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001432 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001433 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001434 I != E; ++I) {
1435 S.Diag(I->first.first, I->first.second);
1436 const OptionalNotes &Notes = I->second;
1437 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1438 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1439 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001440 }
1441
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001442 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001443 PartialDiagnosticAt Warning(Loc,
1444 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1445 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001446 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001447 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1448 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1449 }
1450
1451 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1452 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1453 }
1454
Richard Smith92286672012-02-03 04:45:26 +00001455 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1456 SourceLocation LocEndOfScope,
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001457 LockErrorKind LEK){
1458 unsigned DiagID = 0;
1459 switch (LEK) {
1460 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001461 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001462 break;
1463 case LEK_LockedSomeLoopIterations:
1464 DiagID = diag::warn_expecting_lock_held_on_loop;
1465 break;
1466 case LEK_LockedAtEndOfFunction:
1467 DiagID = diag::warn_no_unlock;
1468 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001469 case LEK_NotLockedAtEndOfFunction:
1470 DiagID = diag::warn_expecting_locked;
1471 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001472 }
Richard Smith92286672012-02-03 04:45:26 +00001473 if (LocEndOfScope.isInvalid())
1474 LocEndOfScope = FunEndLocation;
1475
1476 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001477 if (LocLocked.isValid()) {
1478 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1479 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1480 return;
1481 }
1482 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001483 }
1484
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001485
1486 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1487 SourceLocation Loc2) {
Richard Smith92286672012-02-03 04:45:26 +00001488 PartialDiagnosticAt Warning(
1489 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1490 PartialDiagnosticAt Note(
1491 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1492 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001493 }
1494
1495 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1496 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001497 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1498 && "Only works for variables");
1499 unsigned DiagID = POK == POK_VarAccess?
1500 diag::warn_variable_requires_any_lock:
1501 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001502 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001503 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001504 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001505 }
1506
1507 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001508 Name LockName, LockKind LK, SourceLocation Loc,
1509 Name *PossibleMatch) {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001510 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001511 if (PossibleMatch) {
1512 switch (POK) {
1513 case POK_VarAccess:
1514 DiagID = diag::warn_variable_requires_lock_precise;
1515 break;
1516 case POK_VarDereference:
1517 DiagID = diag::warn_var_deref_requires_lock_precise;
1518 break;
1519 case POK_FunctionCall:
1520 DiagID = diag::warn_fun_requires_lock_precise;
1521 break;
1522 }
1523 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001524 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001525 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1526 << *PossibleMatch);
1527 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1528 } else {
1529 switch (POK) {
1530 case POK_VarAccess:
1531 DiagID = diag::warn_variable_requires_lock;
1532 break;
1533 case POK_VarDereference:
1534 DiagID = diag::warn_var_deref_requires_lock;
1535 break;
1536 case POK_FunctionCall:
1537 DiagID = diag::warn_fun_requires_lock;
1538 break;
1539 }
1540 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001541 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001542 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001543 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001544 }
1545
1546 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith92286672012-02-03 04:45:26 +00001547 PartialDiagnosticAt Warning(Loc,
1548 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1549 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001550 }
1551};
1552}
1553}
David Blaikie68e081d2011-12-20 02:48:34 +00001554}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001555
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001556//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001557// -Wconsumed
1558//===----------------------------------------------------------------------===//
1559
1560namespace clang {
1561namespace consumed {
1562namespace {
1563class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1564
1565 Sema &S;
1566 DiagList Warnings;
1567
1568public:
1569
1570 ConsumedWarningsHandler(Sema &S) : S(S) {}
1571
1572 void emitDiagnostics() {
1573 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1574
1575 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1576 I != E; ++I) {
1577
1578 const OptionalNotes &Notes = I->second;
1579 S.Diag(I->first.first, I->first.second);
1580
1581 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1582 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1583 }
1584 }
1585 }
1586
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001587 void warnLoopStateMismatch(SourceLocation Loc, StringRef VariableName) {
1588 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1589 VariableName);
1590
1591 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1592 }
1593
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001594 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1595 StringRef VariableName,
1596 StringRef ExpectedState,
1597 StringRef ObservedState) {
1598
1599 PartialDiagnosticAt Warning(Loc, S.PDiag(
1600 diag::warn_param_return_typestate_mismatch) << VariableName <<
1601 ExpectedState << ObservedState);
1602
1603 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1604 }
1605
DeLesley Hutchins69391772013-10-17 23:23:53 +00001606 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1607 StringRef ObservedState) {
1608
1609 PartialDiagnosticAt Warning(Loc, S.PDiag(
1610 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1611
1612 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1613 }
1614
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001615 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1616 StringRef TypeName) {
1617 PartialDiagnosticAt Warning(Loc, S.PDiag(
1618 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1619
1620 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1621 }
1622
1623 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1624 StringRef ObservedState) {
1625
1626 PartialDiagnosticAt Warning(Loc, S.PDiag(
1627 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1628
1629 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1630 }
1631
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001632 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1633 SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001634
1635 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001636 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001637
1638 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1639 }
1640
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001641 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1642 StringRef State, SourceLocation Loc) {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001643
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001644 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1645 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001646
1647 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1648 }
1649};
1650}}}
1651
1652//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001653// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1654// warnings on a function, method, or block.
1655//===----------------------------------------------------------------------===//
1656
Ted Kremenek0b405322010-03-23 00:13:23 +00001657clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1658 enableCheckFallThrough = 1;
1659 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001660 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001661 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001662}
1663
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001664clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1665 : S(s),
1666 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001667 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001668 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001669 MaxCFGBlocksPerFunction(0),
1670 NumUninitAnalysisFunctions(0),
1671 NumUninitAnalysisVariables(0),
1672 MaxUninitAnalysisVariablesPerFunction(0),
1673 NumUninitAnalysisBlockVisits(0),
1674 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikie9c902b52011-09-25 23:23:43 +00001675 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenek0b405322010-03-23 00:13:23 +00001676 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001677 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001678 DiagnosticsEngine::Ignored);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001679 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1680 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001681 DiagnosticsEngine::Ignored);
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001682 DefaultPolicy.enableConsumedAnalysis = (unsigned)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001683 (D.getDiagnosticLevel(diag::warn_use_in_invalid_state, SourceLocation()) !=
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001684 DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +00001685}
1686
Ted Kremenek3427fac2011-02-23 01:52:04 +00001687static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001688 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001689 i = fscope->PossiblyUnreachableDiags.begin(),
1690 e = fscope->PossiblyUnreachableDiags.end();
1691 i != e; ++i) {
1692 const sema::PossiblyUnreachableDiag &D = *i;
1693 S.Diag(D.Loc, D.PD);
1694 }
1695}
1696
Ted Kremenek0b405322010-03-23 00:13:23 +00001697void clang::sema::
1698AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001699 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001700 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001701
Ted Kremenek918fe842010-03-20 21:06:02 +00001702 // We avoid doing analysis-based warnings when there are errors for
1703 // two reasons:
1704 // (1) The CFGs often can't be constructed (if the body is invalid), so
1705 // don't bother trying.
1706 // (2) The code already has problems; running the analysis just takes more
1707 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001708 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001709
Ted Kremenek0b405322010-03-23 00:13:23 +00001710 // Do not do any analysis for declarations in system headers if we are
1711 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001712 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001713 S.SourceMgr.isInSystemHeader(D->getLocation()))
1714 return;
1715
John McCall1d570a72010-08-25 05:56:39 +00001716 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001717 if (cast<DeclContext>(D)->isDependentContext())
1718 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001719
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001720 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001721 // Flush out any possibly unreachable diagnostics.
1722 flushDiagnostics(S, fscope);
1723 return;
1724 }
1725
Ted Kremenek918fe842010-03-20 21:06:02 +00001726 const Stmt *Body = D->getBody();
1727 assert(Body);
1728
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001729 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001730 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001731
Ted Kremenek918fe842010-03-20 21:06:02 +00001732 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001733 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001734 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1735 AC.getCFGBuildOptions().AddEHEdges = false;
1736 AC.getCFGBuildOptions().AddInitializers = true;
1737 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001738 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001739 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001740
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001741 // Force that certain expressions appear as CFGElements in the CFG. This
1742 // is used to speed up various analyses.
1743 // FIXME: This isn't the right factoring. This is here for initial
1744 // prototyping, but we need a way for analyses to say what expressions they
1745 // expect to always be CFGElements and then fill in the BuildOptions
1746 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001747 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1748 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001749 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001750 AC.getCFGBuildOptions().setAllAlwaysAdd();
1751 }
1752 else {
1753 AC.getCFGBuildOptions()
1754 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001755 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001756 .setAlwaysAdd(Stmt::BlockExprClass)
1757 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1758 .setAlwaysAdd(Stmt::DeclRefExprClass)
1759 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001760 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1761 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001762 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001763
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001764
Ted Kremenek3427fac2011-02-23 01:52:04 +00001765 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001766 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001767 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001768
1769 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001770 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001771 i = fscope->PossiblyUnreachableDiags.begin(),
1772 e = fscope->PossiblyUnreachableDiags.end();
1773 i != e; ++i) {
1774 if (const Stmt *stmt = i->stmt)
1775 AC.registerForcedBlockExpression(stmt);
1776 }
1777
1778 if (AC.getCFG()) {
1779 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001780 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001781 i = fscope->PossiblyUnreachableDiags.begin(),
1782 e = fscope->PossiblyUnreachableDiags.end();
1783 i != e; ++i)
1784 {
1785 const sema::PossiblyUnreachableDiag &D = *i;
1786 bool processed = false;
1787 if (const Stmt *stmt = i->stmt) {
1788 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001789 CFGReverseBlockReachabilityAnalysis *cra =
1790 AC.getCFGReachablityAnalysis();
1791 // FIXME: We should be able to assert that block is non-null, but
1792 // the CFG analysis can skip potentially-evaluated expressions in
1793 // edge cases; see test/Sema/vla-2.c.
1794 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001795 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001796 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001797 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001798 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001799 }
1800 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001801 if (!processed) {
1802 // Emit the warning anyway if we cannot map to a basic block.
1803 S.Diag(D.Loc, D.PD);
1804 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001805 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001806 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001807
1808 if (!analyzed)
1809 flushDiagnostics(S, fscope);
1810 }
1811
1812
Ted Kremenek918fe842010-03-20 21:06:02 +00001813 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001814 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001815 const CheckFallThroughDiagnostics &CD =
1816 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001817 : (isa<CXXMethodDecl>(D) &&
1818 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1819 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1820 ? CheckFallThroughDiagnostics::MakeForLambda()
1821 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001822 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001823 }
1824
1825 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001826 if (P.enableCheckUnreachable) {
1827 // Only check for unreachable code on non-template instantiations.
1828 // Different template instantiations can effectively change the control-flow
1829 // and it is very difficult to prove that a snippet of code in a template
1830 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001831 bool isTemplateInstantiation = false;
1832 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1833 isTemplateInstantiation = Function->isTemplateInstantiation();
1834 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001835 CheckUnreachable(S, AC);
1836 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001837
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001838 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001839 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001840 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001841 SourceLocation FEL = AC.getDecl()->getLocEnd();
1842 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001843 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1844 != DiagnosticsEngine::Ignored)
1845 Reporter.setIssueBetaWarnings(true);
1846
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001847 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1848 Reporter.emitDiagnostics();
1849 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001850
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001851 // Check for violations of consumed properties.
1852 if (P.enableConsumedAnalysis) {
1853 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001854 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001855 Analyzer.run(AC);
1856 }
1857
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001858 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001859 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001860 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1861 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001862 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001863 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001864 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001865 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001866 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001867 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001868 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001869 reporter, stats);
1870
1871 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1872 ++NumUninitAnalysisFunctions;
1873 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1874 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1875 MaxUninitAnalysisVariablesPerFunction =
1876 std::max(MaxUninitAnalysisVariablesPerFunction,
1877 stats.NumVariablesAnalyzed);
1878 MaxUninitAnalysisBlockVisitsPerFunction =
1879 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1880 stats.NumBlockVisits);
1881 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001882 }
1883 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001884
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001885 bool FallThroughDiagFull =
1886 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1887 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001888 bool FallThroughDiagPerFunction =
1889 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001890 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001891 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001892 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001893 }
1894
Jordan Rosed3934582012-09-28 22:21:30 +00001895 if (S.getLangOpts().ObjCARCWeak &&
1896 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1897 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001898 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001899
Richard Trieu2f024f42013-12-21 02:33:43 +00001900
1901 // Check for infinite self-recursion in functions
1902 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1903 D->getLocStart())
1904 != DiagnosticsEngine::Ignored) {
1905 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1906 checkRecursiveFunction(S, FD, Body, AC);
1907 }
1908 }
1909
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001910 // Collect statistics about the CFG if it was built.
1911 if (S.CollectStats && AC.isCFGBuilt()) {
1912 ++NumFunctionsAnalyzed;
1913 if (CFG *cfg = AC.getCFG()) {
1914 // If we successfully built a CFG for this context, record some more
1915 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001916 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001917 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001918 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001919 } else {
1920 ++NumFunctionsWithBadCFGs;
1921 }
1922 }
1923}
1924
1925void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1926 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1927
1928 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1929 unsigned AvgCFGBlocksPerFunction =
1930 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1931 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1932 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1933 << " " << NumCFGBlocks << " CFG blocks built.\n"
1934 << " " << AvgCFGBlocksPerFunction
1935 << " average CFG blocks per function.\n"
1936 << " " << MaxCFGBlocksPerFunction
1937 << " max CFG blocks per function.\n";
1938
1939 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1940 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1941 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1942 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1943 llvm::errs() << NumUninitAnalysisFunctions
1944 << " functions analyzed for uninitialiazed variables\n"
1945 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1946 << " " << AvgUninitVariablesPerFunction
1947 << " average variables per function.\n"
1948 << " " << MaxUninitAnalysisVariablesPerFunction
1949 << " max variables per function.\n"
1950 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1951 << " " << AvgUninitBlockVisitsPerFunction
1952 << " average block visits per function.\n"
1953 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1954 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001955}