blob: dabac1e6c4c19a0873e3d1e535a315a81839dc10 [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
Craig Toppere14c0f82014-03-12 04:55:44 +000068 void HandleUnreachable(SourceLocation L, SourceRange R1,
69 SourceRange R2) override {
Ted Kremenek918fe842010-03-20 21:06:02 +000070 S.Diag(L, diag::warn_unreachable) << R1 << R2;
71 }
72 };
73}
74
75/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +000076static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +000077 // As a heuristic prune all diagnostics not in the main file. Currently
78 // the majority of warnings in headers are false positives. These
79 // are largely caused by configuration state, e.g. preprocessor
80 // defined code, etc.
81 //
82 // Note that this is also a performance optimization. Analyzing
83 // headers many times can be expensive.
84 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
85 return;
86
Ted Kremenek918fe842010-03-20 21:06:02 +000087 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +000088 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +000089}
90
91//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +000092// Check for infinite self-recursion in functions
93//===----------------------------------------------------------------------===//
94
95// All blocks are in one of three states. States are ordered so that blocks
96// can only move to higher states.
97enum RecursiveState {
98 FoundNoPath,
99 FoundPath,
100 FoundPathWithNoRecursiveCall
101};
102
103static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
104 CFGBlock &Block, unsigned ExitID,
105 llvm::SmallVectorImpl<RecursiveState> &States,
106 RecursiveState State) {
107 unsigned ID = Block.getBlockID();
108
109 // A block's state can only move to a higher state.
110 if (States[ID] >= State)
111 return;
112
113 States[ID] = State;
114
115 // Found a path to the exit node without a recursive call.
116 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
117 return;
118
119 if (State == FoundPathWithNoRecursiveCall) {
120 // If the current state is FoundPathWithNoRecursiveCall, the successors
121 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
122 // which, process all the Stmt's in this block to find any recursive calls.
123 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
124 if (I->getKind() != CFGElement::Statement)
125 continue;
126
127 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
128 if (CE && CE->getCalleeDecl() &&
129 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000130
131 // Skip function calls which are qualified with a templated class.
132 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
133 CE->getCallee()->IgnoreParenImpCasts())) {
134 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
135 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
136 isa<TemplateSpecializationType>(NNS->getAsType())) {
137 continue;
138 }
139 }
140 }
141
Richard Trieu2f024f42013-12-21 02:33:43 +0000142 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
143 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
144 !MCE->getMethodDecl()->isVirtual()) {
145 State = FoundPath;
146 break;
147 }
148 } else {
149 State = FoundPath;
150 break;
151 }
152 }
153 }
154 }
155
156 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
157 I != E; ++I)
158 if (*I)
159 checkForFunctionCall(S, FD, **I, ExitID, States, State);
160}
161
162static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
163 const Stmt *Body,
164 AnalysisDeclContext &AC) {
165 FD = FD->getCanonicalDecl();
166
167 // Only run on non-templated functions and non-templated members of
168 // templated classes.
169 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
170 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
171 return;
172
173 CFG *cfg = AC.getCFG();
174 if (cfg == 0) return;
175
176 // If the exit block is unreachable, skip processing the function.
177 if (cfg->getExit().pred_empty())
178 return;
179
180 // Mark all nodes as FoundNoPath, then begin processing the entry block.
181 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
182 FoundNoPath);
183 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
184 states, FoundPathWithNoRecursiveCall);
185
186 // Check that the exit block is reachable. This prevents triggering the
187 // warning on functions that do not terminate.
188 if (states[cfg->getExit().getBlockID()] == FoundPath)
189 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
190}
191
192//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000193// Check for missing return value.
194//===----------------------------------------------------------------------===//
195
John McCall5c6ec8c2010-05-16 09:34:11 +0000196enum ControlFlowKind {
197 UnknownFallThrough,
198 NeverFallThrough,
199 MaybeFallThrough,
200 AlwaysFallThrough,
201 NeverFallThroughOrReturn
202};
Ted Kremenek918fe842010-03-20 21:06:02 +0000203
204/// CheckFallThrough - Check that we don't fall off the end of a
205/// Statement that should return a value.
206///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000207/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
208/// MaybeFallThrough iff we might or might not fall off the end,
209/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
210/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000211/// statement but we may return. We assume that functions not marked noreturn
212/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000213static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000214 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000215 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000216
217 // The CFG leaves in dead things, and we don't want the dead code paths to
218 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000219 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000220 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000221 live);
222
223 bool AddEHEdges = AC.getAddEHEdges();
224 if (!AddEHEdges && count != cfg->getNumBlockIDs())
225 // When there are things remaining dead, and we didn't add EH edges
226 // from CallExprs to the catch clauses, we have to go back and
227 // mark them as live.
228 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
229 CFGBlock &b = **I;
230 if (!live[b.getBlockID()]) {
231 if (b.pred_begin() == b.pred_end()) {
232 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
233 // When not adding EH edges from calls, catch clauses
234 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000235 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000236 continue;
237 }
238 }
239 }
240
241 // Now we know what is live, we check the live precessors of the exit block
242 // and look for fall through paths, being careful to ignore normal returns,
243 // and exceptional paths.
244 bool HasLiveReturn = false;
245 bool HasFakeEdge = false;
246 bool HasPlainEdge = false;
247 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000248
249 // Ignore default cases that aren't likely to be reachable because all
250 // enums in a switch(X) have explicit case statements.
251 CFGBlock::FilterOptions FO;
252 FO.IgnoreDefaultsWithCoveredEnums = 1;
253
254 for (CFGBlock::filtered_pred_iterator
255 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
256 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000257 if (!live[B.getBlockID()])
258 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000259
Chandler Carruth03faf782011-09-13 09:53:58 +0000260 // Skip blocks which contain an element marked as no-return. They don't
261 // represent actually viable edges into the exit block, so mark them as
262 // abnormal.
263 if (B.hasNoReturnElement()) {
264 HasAbnormalEdge = true;
265 continue;
266 }
267
Ted Kremenek5d068492011-01-26 04:49:52 +0000268 // Destructors can appear after the 'return' in the CFG. This is
269 // normal. We need to look pass the destructors for the return
270 // statement (if it exists).
271 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000272
Chandler Carruth03faf782011-09-13 09:53:58 +0000273 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000274 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000275 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000276
Ted Kremenek5d068492011-01-26 04:49:52 +0000277 // No more CFGElements in the block?
278 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000279 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
280 HasAbnormalEdge = true;
281 continue;
282 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000283 // A labeled empty statement, or the entry block...
284 HasPlainEdge = true;
285 continue;
286 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000287
David Blaikie2a01f5d2013-02-21 20:58:29 +0000288 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000289 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000290 if (isa<ReturnStmt>(S)) {
291 HasLiveReturn = true;
292 continue;
293 }
294 if (isa<ObjCAtThrowStmt>(S)) {
295 HasFakeEdge = true;
296 continue;
297 }
298 if (isa<CXXThrowExpr>(S)) {
299 HasFakeEdge = true;
300 continue;
301 }
Chad Rosier32503022012-06-11 20:47:18 +0000302 if (isa<MSAsmStmt>(S)) {
303 // TODO: Verify this is correct.
304 HasFakeEdge = true;
305 HasLiveReturn = true;
306 continue;
307 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000308 if (isa<CXXTryStmt>(S)) {
309 HasAbnormalEdge = true;
310 continue;
311 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000312 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
313 == B.succ_end()) {
314 HasAbnormalEdge = true;
315 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000316 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000317
318 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000319 }
320 if (!HasPlainEdge) {
321 if (HasLiveReturn)
322 return NeverFallThrough;
323 return NeverFallThroughOrReturn;
324 }
325 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
326 return MaybeFallThrough;
327 // This says AlwaysFallThrough for calls to functions that are not marked
328 // noreturn, that don't return. If people would like this warning to be more
329 // accurate, such functions should be marked as noreturn.
330 return AlwaysFallThrough;
331}
332
Dan Gohman28ade552010-07-26 21:25:24 +0000333namespace {
334
Ted Kremenek918fe842010-03-20 21:06:02 +0000335struct CheckFallThroughDiagnostics {
336 unsigned diag_MaybeFallThrough_HasNoReturn;
337 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
338 unsigned diag_AlwaysFallThrough_HasNoReturn;
339 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
340 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000341 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000342 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000343
Douglas Gregor24f27692010-04-16 23:28:44 +0000344 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000345 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000346 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000347 D.diag_MaybeFallThrough_HasNoReturn =
348 diag::warn_falloff_noreturn_function;
349 D.diag_MaybeFallThrough_ReturnsNonVoid =
350 diag::warn_maybe_falloff_nonvoid_function;
351 D.diag_AlwaysFallThrough_HasNoReturn =
352 diag::warn_falloff_noreturn_function;
353 D.diag_AlwaysFallThrough_ReturnsNonVoid =
354 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000355
356 // Don't suggest that virtual functions be marked "noreturn", since they
357 // might be overridden by non-noreturn functions.
358 bool isVirtualMethod = false;
359 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
360 isVirtualMethod = Method->isVirtual();
361
Douglas Gregor0de57202011-10-10 18:15:57 +0000362 // Don't suggest that template instantiations be marked "noreturn"
363 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000364 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
365 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000366
367 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000368 D.diag_NeverFallThroughOrReturn =
369 diag::warn_suggest_noreturn_function;
370 else
371 D.diag_NeverFallThroughOrReturn = 0;
372
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000373 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000374 return D;
375 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000376
Ted Kremenek918fe842010-03-20 21:06:02 +0000377 static CheckFallThroughDiagnostics MakeForBlock() {
378 CheckFallThroughDiagnostics D;
379 D.diag_MaybeFallThrough_HasNoReturn =
380 diag::err_noreturn_block_has_return_expr;
381 D.diag_MaybeFallThrough_ReturnsNonVoid =
382 diag::err_maybe_falloff_nonvoid_block;
383 D.diag_AlwaysFallThrough_HasNoReturn =
384 diag::err_noreturn_block_has_return_expr;
385 D.diag_AlwaysFallThrough_ReturnsNonVoid =
386 diag::err_falloff_nonvoid_block;
387 D.diag_NeverFallThroughOrReturn =
388 diag::warn_suggest_noreturn_block;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000389 D.funMode = Block;
390 return D;
391 }
392
393 static CheckFallThroughDiagnostics MakeForLambda() {
394 CheckFallThroughDiagnostics D;
395 D.diag_MaybeFallThrough_HasNoReturn =
396 diag::err_noreturn_lambda_has_return_expr;
397 D.diag_MaybeFallThrough_ReturnsNonVoid =
398 diag::warn_maybe_falloff_nonvoid_lambda;
399 D.diag_AlwaysFallThrough_HasNoReturn =
400 diag::err_noreturn_lambda_has_return_expr;
401 D.diag_AlwaysFallThrough_ReturnsNonVoid =
402 diag::warn_falloff_nonvoid_lambda;
403 D.diag_NeverFallThroughOrReturn = 0;
404 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000405 return D;
406 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000407
David Blaikie9c902b52011-09-25 23:23:43 +0000408 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000409 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000410 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000411 return (ReturnsVoid ||
412 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000413 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000414 && (!HasNoReturn ||
415 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000416 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000417 && (!ReturnsVoid ||
418 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000419 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000420 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000421
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000422 // For blocks / lambdas.
423 return ReturnsVoid && !HasNoReturn
424 && ((funMode == Lambda) ||
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000425 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000426 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000427 }
428};
429
Dan Gohman28ade552010-07-26 21:25:24 +0000430}
431
Ted Kremenek918fe842010-03-20 21:06:02 +0000432/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
433/// function that should return a value. Check that we don't fall off the end
434/// of a noreturn function. We assume that functions and blocks not marked
435/// noreturn will return.
436static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000437 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000438 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000439 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000440
441 bool ReturnsVoid = false;
442 bool HasNoReturn = false;
443
444 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000445 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000446 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000447 }
448 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000449 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000450 HasNoReturn = MD->hasAttr<NoReturnAttr>();
451 }
452 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000453 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000454 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000455 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000456 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000457 ReturnsVoid = true;
458 if (FT->getNoReturnAttr())
459 HasNoReturn = true;
460 }
461 }
462
David Blaikie9c902b52011-09-25 23:23:43 +0000463 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000464
465 // Short circuit for compilation speed.
466 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
467 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000468
Ted Kremenek918fe842010-03-20 21:06:02 +0000469 // FIXME: Function try block
470 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
471 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000472 case UnknownFallThrough:
473 break;
474
Ted Kremenek918fe842010-03-20 21:06:02 +0000475 case MaybeFallThrough:
476 if (HasNoReturn)
477 S.Diag(Compound->getRBracLoc(),
478 CD.diag_MaybeFallThrough_HasNoReturn);
479 else if (!ReturnsVoid)
480 S.Diag(Compound->getRBracLoc(),
481 CD.diag_MaybeFallThrough_ReturnsNonVoid);
482 break;
483 case AlwaysFallThrough:
484 if (HasNoReturn)
485 S.Diag(Compound->getRBracLoc(),
486 CD.diag_AlwaysFallThrough_HasNoReturn);
487 else if (!ReturnsVoid)
488 S.Diag(Compound->getRBracLoc(),
489 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
490 break;
491 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000492 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
493 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
494 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000495 << 0 << FD;
496 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
497 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
498 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000499 } else {
500 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
501 }
502 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000503 break;
504 case NeverFallThrough:
505 break;
506 }
507 }
508}
509
510//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000511// -Wuninitialized
512//===----------------------------------------------------------------------===//
513
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000514namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000515/// ContainsReference - A visitor class to search for references to
516/// a particular declaration (the needle) within any evaluated component of an
517/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000518class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000519 bool FoundReference;
520 const DeclRefExpr *Needle;
521
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000522public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000523 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
524 : EvaluatedExprVisitor<ContainsReference>(Context),
525 FoundReference(false), Needle(Needle) {}
526
527 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000528 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000529 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000530 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000531
532 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000533 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000534
535 void VisitDeclRefExpr(DeclRefExpr *E) {
536 if (E == Needle)
537 FoundReference = true;
538 else
539 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000540 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000541
542 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000543};
544}
545
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000546static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000547 QualType VariableTy = VD->getType().getCanonicalType();
548 if (VariableTy->isBlockPointerType() &&
549 !VD->hasAttr<BlocksAttr>()) {
550 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
551 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
552 return true;
553 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000554
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000555 // Don't issue a fixit if there is already an initializer.
556 if (VD->getInit())
557 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000558
559 // Don't suggest a fixit inside macros.
560 if (VD->getLocEnd().isMacroID())
561 return false;
562
Richard Smith8d06f422012-01-12 23:53:29 +0000563 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000564
565 // Suggest possible initialization (if any).
566 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
567 if (Init.empty())
568 return false;
569
Richard Smith8d06f422012-01-12 23:53:29 +0000570 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
571 << FixItHint::CreateInsertion(Loc, Init);
572 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000573}
574
Richard Smith1bb8edb82012-05-26 06:20:46 +0000575/// Create a fixit to remove an if-like statement, on the assumption that its
576/// condition is CondVal.
577static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
578 const Stmt *Else, bool CondVal,
579 FixItHint &Fixit1, FixItHint &Fixit2) {
580 if (CondVal) {
581 // If condition is always true, remove all but the 'then'.
582 Fixit1 = FixItHint::CreateRemoval(
583 CharSourceRange::getCharRange(If->getLocStart(),
584 Then->getLocStart()));
585 if (Else) {
586 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
587 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
588 Fixit2 = FixItHint::CreateRemoval(
589 SourceRange(ElseKwLoc, Else->getLocEnd()));
590 }
591 } else {
592 // If condition is always false, remove all but the 'else'.
593 if (Else)
594 Fixit1 = FixItHint::CreateRemoval(
595 CharSourceRange::getCharRange(If->getLocStart(),
596 Else->getLocStart()));
597 else
598 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
599 }
600}
601
602/// DiagUninitUse -- Helper function to produce a diagnostic for an
603/// uninitialized use of a variable.
604static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
605 bool IsCapturedByBlock) {
606 bool Diagnosed = false;
607
Richard Smithba8071e2013-09-12 18:49:10 +0000608 switch (Use.getKind()) {
609 case UninitUse::Always:
610 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
611 << VD->getDeclName() << IsCapturedByBlock
612 << Use.getUser()->getSourceRange();
613 return;
614
615 case UninitUse::AfterDecl:
616 case UninitUse::AfterCall:
617 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
618 << VD->getDeclName() << IsCapturedByBlock
619 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
620 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
621 << VD->getSourceRange();
622 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
623 << IsCapturedByBlock << Use.getUser()->getSourceRange();
624 return;
625
626 case UninitUse::Maybe:
627 case UninitUse::Sometimes:
628 // Carry on to report sometimes-uninitialized branches, if possible,
629 // or a 'may be used uninitialized' diagnostic otherwise.
630 break;
631 }
632
Richard Smith1bb8edb82012-05-26 06:20:46 +0000633 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000634 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
635 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000636 assert(Use.getKind() == UninitUse::Sometimes);
637
638 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000639 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000640
641 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000642 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000643 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000644 SourceRange Range;
645
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000646 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000647 // For all binary terminators, branch 0 is taken if the condition is true,
648 // and branch 1 is taken if the condition is false.
649 int RemoveDiagKind = -1;
650 const char *FixitStr =
651 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
652 : (I->Output ? "1" : "0");
653 FixItHint Fixit1, Fixit2;
654
Richard Smithba8071e2013-09-12 18:49:10 +0000655 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000656 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000657 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000658 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000659 continue;
660
661 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000662 case Stmt::IfStmtClass: {
663 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000664 DiagKind = 0;
665 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000666 Range = IS->getCond()->getSourceRange();
667 RemoveDiagKind = 0;
668 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
669 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000670 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000671 }
672 case Stmt::ConditionalOperatorClass: {
673 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000674 DiagKind = 0;
675 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000676 Range = CO->getCond()->getSourceRange();
677 RemoveDiagKind = 0;
678 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
679 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000680 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000681 }
Richard Smith4323bf82012-05-25 02:17:09 +0000682 case Stmt::BinaryOperatorClass: {
683 const BinaryOperator *BO = cast<BinaryOperator>(Term);
684 if (!BO->isLogicalOp())
685 continue;
686 DiagKind = 0;
687 Str = BO->getOpcodeStr();
688 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000689 RemoveDiagKind = 0;
690 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
691 (BO->getOpcode() == BO_LOr && !I->Output))
692 // true && y -> y, false || y -> y.
693 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
694 BO->getOperatorLoc()));
695 else
696 // false && y -> false, true || y -> true.
697 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000698 break;
699 }
700
701 // "loop is entered / loop is exited".
702 case Stmt::WhileStmtClass:
703 DiagKind = 1;
704 Str = "while";
705 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000706 RemoveDiagKind = 1;
707 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000708 break;
709 case Stmt::ForStmtClass:
710 DiagKind = 1;
711 Str = "for";
712 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000713 RemoveDiagKind = 1;
714 if (I->Output)
715 Fixit1 = FixItHint::CreateRemoval(Range);
716 else
717 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000718 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000719 case Stmt::CXXForRangeStmtClass:
720 if (I->Output == 1) {
721 // The use occurs if a range-based for loop's body never executes.
722 // That may be impossible, and there's no syntactic fix for this,
723 // so treat it as a 'may be uninitialized' case.
724 continue;
725 }
726 DiagKind = 1;
727 Str = "for";
728 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
729 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000730
731 // "condition is true / loop is exited".
732 case Stmt::DoStmtClass:
733 DiagKind = 2;
734 Str = "do";
735 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000736 RemoveDiagKind = 1;
737 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000738 break;
739
740 // "switch case is taken".
741 case Stmt::CaseStmtClass:
742 DiagKind = 3;
743 Str = "case";
744 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
745 break;
746 case Stmt::DefaultStmtClass:
747 DiagKind = 3;
748 Str = "default";
749 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
750 break;
751 }
752
Richard Smith1bb8edb82012-05-26 06:20:46 +0000753 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
754 << VD->getDeclName() << IsCapturedByBlock << DiagKind
755 << Str << I->Output << Range;
756 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
757 << IsCapturedByBlock << User->getSourceRange();
758 if (RemoveDiagKind != -1)
759 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
760 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
761
762 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000763 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000764
765 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000766 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000767 << VD->getDeclName() << IsCapturedByBlock
768 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000769}
770
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000771/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
772/// uninitialized variable. This manages the different forms of diagnostic
773/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000774/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000775/// false.
776static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000777 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000778 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000779
Richard Smith4323bf82012-05-25 02:17:09 +0000780 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000781 // Inspect the initializer of the variable declaration which is
782 // being referenced prior to its initialization. We emit
783 // specialized diagnostics for self-initialization, and we
784 // specifically avoid warning about self references which take the
785 // form of:
786 //
787 // int x = x;
788 //
789 // This is used to indicate to GCC that 'x' is intentionally left
790 // uninitialized. Proven code paths which access 'x' in
791 // an uninitialized state after this will still warn.
792 if (const Expr *Initializer = VD->getInit()) {
793 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
794 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000795
Richard Trieu43a2fc72012-05-09 21:08:22 +0000796 ContainsReference CR(S.Context, DRE);
797 CR.Visit(const_cast<Expr*>(Initializer));
798 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000799 S.Diag(DRE->getLocStart(),
800 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000801 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
802 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000803 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000804 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000805
Richard Smith1bb8edb82012-05-26 06:20:46 +0000806 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000807 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000808 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000809 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
810 S.Diag(BE->getLocStart(),
811 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000812 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000813 else
814 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000815 }
816
817 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000818 // the initializer of that declaration & we didn't already suggest
819 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000820 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000821 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
822 << VD->getDeclName();
823
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000824 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000825}
826
Richard Smith84837d52012-05-03 18:27:39 +0000827namespace {
828 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
829 public:
830 FallthroughMapper(Sema &S)
831 : FoundSwitchStatements(false),
832 S(S) {
833 }
834
835 bool foundSwitchStatements() const { return FoundSwitchStatements; }
836
837 void markFallthroughVisited(const AttributedStmt *Stmt) {
838 bool Found = FallthroughStmts.erase(Stmt);
839 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000840 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000841 }
842
843 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
844
845 const AttrStmts &getFallthroughStmts() const {
846 return FallthroughStmts;
847 }
848
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000849 void fillReachableBlocks(CFG *Cfg) {
850 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
851 std::deque<const CFGBlock *> BlockQueue;
852
853 ReachableBlocks.insert(&Cfg->getEntry());
854 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000855 // Mark all case blocks reachable to avoid problems with switching on
856 // constants, covered enums, etc.
857 // These blocks can contain fall-through annotations, and we don't want to
858 // issue a warn_fallthrough_attr_unreachable for them.
859 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
860 const CFGBlock *B = *I;
861 const Stmt *L = B->getLabel();
862 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
863 BlockQueue.push_back(B);
864 }
865
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000866 while (!BlockQueue.empty()) {
867 const CFGBlock *P = BlockQueue.front();
868 BlockQueue.pop_front();
869 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
870 E = P->succ_end();
871 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000872 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000873 BlockQueue.push_back(*I);
874 }
875 }
876 }
877
Richard Smith84837d52012-05-03 18:27:39 +0000878 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000879 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
880
Richard Smith84837d52012-05-03 18:27:39 +0000881 int UnannotatedCnt = 0;
882 AnnotatedCnt = 0;
883
884 std::deque<const CFGBlock*> BlockQueue;
885
886 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
887
888 while (!BlockQueue.empty()) {
889 const CFGBlock *P = BlockQueue.front();
890 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000891 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000892
893 const Stmt *Term = P->getTerminator();
894 if (Term && isa<SwitchStmt>(Term))
895 continue; // Switch statement, good.
896
897 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
898 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
899 continue; // Previous case label has no statements, good.
900
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000901 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
902 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
903 continue; // Case label is preceded with a normal label, good.
904
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000905 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000906 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
907 ElemEnd = P->rend();
908 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000909 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
910 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000911 S.Diag(AS->getLocStart(),
912 diag::warn_fallthrough_attr_unreachable);
913 markFallthroughVisited(AS);
914 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000915 break;
Richard Smith84837d52012-05-03 18:27:39 +0000916 }
917 // Don't care about other unreachable statements.
918 }
919 }
920 // If there are no unreachable statements, this may be a special
921 // case in CFG:
922 // case X: {
923 // A a; // A has a destructor.
924 // break;
925 // }
926 // // <<<< This place is represented by a 'hanging' CFG block.
927 // case Y:
928 continue;
929 }
930
931 const Stmt *LastStmt = getLastStmt(*P);
932 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
933 markFallthroughVisited(AS);
934 ++AnnotatedCnt;
935 continue; // Fallthrough annotation, good.
936 }
937
938 if (!LastStmt) { // This block contains no executable statements.
939 // Traverse its predecessors.
940 std::copy(P->pred_begin(), P->pred_end(),
941 std::back_inserter(BlockQueue));
942 continue;
943 }
944
945 ++UnannotatedCnt;
946 }
947 return !!UnannotatedCnt;
948 }
949
950 // RecursiveASTVisitor setup.
951 bool shouldWalkTypesOfTypeLocs() const { return false; }
952
953 bool VisitAttributedStmt(AttributedStmt *S) {
954 if (asFallThroughAttr(S))
955 FallthroughStmts.insert(S);
956 return true;
957 }
958
959 bool VisitSwitchStmt(SwitchStmt *S) {
960 FoundSwitchStatements = true;
961 return true;
962 }
963
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +0000964 // We don't want to traverse local type declarations. We analyze their
965 // methods separately.
966 bool TraverseDecl(Decl *D) { return true; }
967
Richard Smith84837d52012-05-03 18:27:39 +0000968 private:
969
970 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
971 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
972 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
973 return AS;
974 }
975 return 0;
976 }
977
978 static const Stmt *getLastStmt(const CFGBlock &B) {
979 if (const Stmt *Term = B.getTerminator())
980 return Term;
981 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
982 ElemEnd = B.rend();
983 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000984 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
985 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +0000986 }
987 // Workaround to detect a statement thrown out by CFGBuilder:
988 // case X: {} case Y:
989 // case X: ; case Y:
990 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
991 if (!isa<SwitchCase>(SW->getSubStmt()))
992 return SW->getSubStmt();
993
994 return 0;
995 }
996
997 bool FoundSwitchStatements;
998 AttrStmts FallthroughStmts;
999 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001000 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001001 };
1002}
1003
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001004static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001005 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001006 // Only perform this analysis when using C++11. There is no good workflow
1007 // for this warning when not using C++11. There is no good way to silence
1008 // the warning (no attribute is available) unless we are using C++11's support
1009 // for generalized attributes. Once could use pragmas to silence the warning,
1010 // but as a general solution that is gross and not in the spirit of this
1011 // warning.
1012 //
1013 // NOTE: This an intermediate solution. There are on-going discussions on
1014 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001015 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001016 return;
1017
Richard Smith84837d52012-05-03 18:27:39 +00001018 FallthroughMapper FM(S);
1019 FM.TraverseStmt(AC.getBody());
1020
1021 if (!FM.foundSwitchStatements())
1022 return;
1023
Alexis Hunt2178f142012-06-15 21:22:05 +00001024 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001025 return;
1026
Richard Smith84837d52012-05-03 18:27:39 +00001027 CFG *Cfg = AC.getCFG();
1028
1029 if (!Cfg)
1030 return;
1031
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001032 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001033
1034 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001035 const CFGBlock *B = *I;
1036 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001037
1038 if (!Label || !isa<SwitchCase>(Label))
1039 continue;
1040
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001041 int AnnotatedCnt;
1042
Alexander Kornienko55488792013-01-25 15:49:34 +00001043 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001044 continue;
1045
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001046 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001047 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1048 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001049
1050 if (!AnnotatedCnt) {
1051 SourceLocation L = Label->getLocStart();
1052 if (L.isMacroID())
1053 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001054 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001055 const Stmt *Term = B->getTerminator();
1056 // Skip empty cases.
1057 while (B->empty() && !Term && B->succ_size() == 1) {
1058 B = *B->succ_begin();
1059 Term = B->getTerminator();
1060 }
1061 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001062 Preprocessor &PP = S.getPreprocessor();
1063 TokenValue Tokens[] = {
1064 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1065 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1066 tok::r_square, tok::r_square
1067 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001068 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1069 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1070 if (!MacroName.empty())
1071 AnnotationSpelling = MacroName;
1072 SmallString<64> TextToInsert(AnnotationSpelling);
1073 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001074 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001075 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001076 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001077 }
Richard Smith84837d52012-05-03 18:27:39 +00001078 }
1079 S.Diag(L, diag::note_insert_break_fixit) <<
1080 FixItHint::CreateInsertion(L, "break; ");
1081 }
1082 }
1083
1084 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1085 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1086 E = Fallthroughs.end();
1087 I != E; ++I) {
1088 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1089 }
1090
1091}
1092
Jordan Rose25c0ea82012-10-29 17:46:47 +00001093static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1094 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001095 assert(S);
1096
1097 do {
1098 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001099 case Stmt::ForStmtClass:
1100 case Stmt::WhileStmtClass:
1101 case Stmt::CXXForRangeStmtClass:
1102 case Stmt::ObjCForCollectionStmtClass:
1103 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001104 case Stmt::DoStmtClass: {
1105 const Expr *Cond = cast<DoStmt>(S)->getCond();
1106 llvm::APSInt Val;
1107 if (!Cond->EvaluateAsInt(Val, Ctx))
1108 return true;
1109 return Val.getBoolValue();
1110 }
Jordan Rose76831c62012-10-11 16:10:19 +00001111 default:
1112 break;
1113 }
1114 } while ((S = PM.getParent(S)));
1115
1116 return false;
1117}
1118
Jordan Rosed3934582012-09-28 22:21:30 +00001119
1120static void diagnoseRepeatedUseOfWeak(Sema &S,
1121 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001122 const Decl *D,
1123 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001124 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1125 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1126 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001127 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1128 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001129
Jordan Rose25c0ea82012-10-29 17:46:47 +00001130 ASTContext &Ctx = S.getASTContext();
1131
Jordan Rosed3934582012-09-28 22:21:30 +00001132 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1133
1134 // Extract all weak objects that are referenced more than once.
1135 SmallVector<StmtUsesPair, 8> UsesByStmt;
1136 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1137 I != E; ++I) {
1138 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001139
1140 // Find the first read of the weak object.
1141 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1142 for ( ; UI != UE; ++UI) {
1143 if (UI->isUnsafe())
1144 break;
1145 }
1146
1147 // If there were only writes to this object, don't warn.
1148 if (UI == UE)
1149 continue;
1150
Jordan Rose76831c62012-10-11 16:10:19 +00001151 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001152 // read is not within a loop, don't warn. Additionally, don't warn in a
1153 // loop if the base object is a local variable -- local variables are often
1154 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001155 if (UI == Uses.begin()) {
1156 WeakUseVector::const_iterator UI2 = UI;
1157 for (++UI2; UI2 != UE; ++UI2)
1158 if (UI2->isUnsafe())
1159 break;
1160
Jordan Rose25c0ea82012-10-29 17:46:47 +00001161 if (UI2 == UE) {
1162 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001163 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001164
1165 const WeakObjectProfileTy &Profile = I->first;
1166 if (!Profile.isExactProfile())
1167 continue;
1168
1169 const NamedDecl *Base = Profile.getBase();
1170 if (!Base)
1171 Base = Profile.getProperty();
1172 assert(Base && "A profile always has a base or property.");
1173
1174 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1175 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1176 continue;
1177 }
Jordan Rose76831c62012-10-11 16:10:19 +00001178 }
1179
Jordan Rosed3934582012-09-28 22:21:30 +00001180 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1181 }
1182
1183 if (UsesByStmt.empty())
1184 return;
1185
1186 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001187 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001188 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001189 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1190 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1191 RHS.first->getLocStart());
1192 });
Jordan Rosed3934582012-09-28 22:21:30 +00001193
1194 // Classify the current code body for better warning text.
1195 // This enum should stay in sync with the cases in
1196 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1197 // FIXME: Should we use a common classification enum and the same set of
1198 // possibilities all throughout Sema?
1199 enum {
1200 Function,
1201 Method,
1202 Block,
1203 Lambda
1204 } FunctionKind;
1205
1206 if (isa<sema::BlockScopeInfo>(CurFn))
1207 FunctionKind = Block;
1208 else if (isa<sema::LambdaScopeInfo>(CurFn))
1209 FunctionKind = Lambda;
1210 else if (isa<ObjCMethodDecl>(D))
1211 FunctionKind = Method;
1212 else
1213 FunctionKind = Function;
1214
1215 // Iterate through the sorted problems and emit warnings for each.
1216 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1217 E = UsesByStmt.end();
1218 I != E; ++I) {
1219 const Stmt *FirstRead = I->first;
1220 const WeakObjectProfileTy &Key = I->second->first;
1221 const WeakUseVector &Uses = I->second->second;
1222
Jordan Rose657b5f42012-09-28 22:21:35 +00001223 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1224 // may not contain enough information to determine that these are different
1225 // properties. We can only be 100% sure of a repeated use in certain cases,
1226 // and we adjust the diagnostic kind accordingly so that the less certain
1227 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001228 unsigned DiagKind;
1229 if (Key.isExactProfile())
1230 DiagKind = diag::warn_arc_repeated_use_of_weak;
1231 else
1232 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1233
Jordan Rose657b5f42012-09-28 22:21:35 +00001234 // Classify the weak object being accessed for better warning text.
1235 // This enum should stay in sync with the cases in
1236 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1237 enum {
1238 Variable,
1239 Property,
1240 ImplicitProperty,
1241 Ivar
1242 } ObjectKind;
1243
1244 const NamedDecl *D = Key.getProperty();
1245 if (isa<VarDecl>(D))
1246 ObjectKind = Variable;
1247 else if (isa<ObjCPropertyDecl>(D))
1248 ObjectKind = Property;
1249 else if (isa<ObjCMethodDecl>(D))
1250 ObjectKind = ImplicitProperty;
1251 else if (isa<ObjCIvarDecl>(D))
1252 ObjectKind = Ivar;
1253 else
1254 llvm_unreachable("Unexpected weak object kind!");
1255
Jordan Rosed3934582012-09-28 22:21:30 +00001256 // Show the first time the object was read.
1257 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001258 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001259 << FirstRead->getSourceRange();
1260
1261 // Print all the other accesses as notes.
1262 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1263 UI != UE; ++UI) {
1264 if (UI->getUseExpr() == FirstRead)
1265 continue;
1266 S.Diag(UI->getUseExpr()->getLocStart(),
1267 diag::note_arc_weak_also_accessed_here)
1268 << UI->getUseExpr()->getSourceRange();
1269 }
1270 }
1271}
1272
Jordan Rosed3934582012-09-28 22:21:30 +00001273namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001274class UninitValsDiagReporter : public UninitVariablesHandler {
1275 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001276 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001277 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001278 // Prefer using MapVector to DenseMap, so that iteration order will be
1279 // the same as insertion order. This is needed to obtain a deterministic
1280 // order of diagnostics when calling flushDiagnostics().
1281 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001282 UsesMap *uses;
1283
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001284public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001285 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1286 ~UninitValsDiagReporter() {
1287 flushDiagnostics();
1288 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001289
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001290 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001291 if (!uses)
1292 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001293
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001294 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001295 if (!V.getPointer())
1296 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001297
Ted Kremenek596fa162011-10-13 18:50:06 +00001298 return V;
1299 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001300
1301 void handleUseOfUninitVariable(const VarDecl *vd,
1302 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001303 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001304 }
1305
Craig Toppere14c0f82014-03-12 04:55:44 +00001306 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001307 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001308 }
1309
1310 void flushDiagnostics() {
1311 if (!uses)
1312 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001313
Ted Kremenek39fa0562011-01-21 19:41:41 +00001314 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1315 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001316 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001317
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001318 UsesVec *vec = V.getPointer();
1319 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001320
1321 // Specially handle the case where we have uses of an uninitialized
1322 // variable, but the root cause is an idiomatic self-init. We want
1323 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001324 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001325 DiagnoseUninitializedUse(S, vd,
1326 UninitUse(vd->getInit()->IgnoreParenCasts(),
1327 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001328 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001329 else {
1330 // Sort the uses by their SourceLocations. While not strictly
1331 // guaranteed to produce them in line/column order, this will provide
1332 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001333 std::sort(vec->begin(), vec->end(),
1334 [](const UninitUse &a, const UninitUse &b) {
1335 // Prefer a more confident report over a less confident one.
1336 if (a.getKind() != b.getKind())
1337 return a.getKind() > b.getKind();
1338 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1339 });
1340
Ted Kremenek596fa162011-10-13 18:50:06 +00001341 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1342 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001343 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1344 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1345
1346 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001347 // Skip further diagnostics for this variable. We try to warn only
1348 // on the first point at which a variable is used uninitialized.
1349 break;
1350 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001351 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001352
1353 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001354 delete vec;
1355 }
1356 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001357 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001358
1359private:
1360 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1361 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001362 if (i->getKind() == UninitUse::Always ||
1363 i->getKind() == UninitUse::AfterCall ||
1364 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001365 return true;
1366 }
1367 }
1368 return false;
1369}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001370};
1371}
1372
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001373namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001374namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001375typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001376typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001377typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001378
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001379struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001380 SourceManager &SM;
1381 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001382
1383 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1384 // Although this call will be slow, this is only called when outputting
1385 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001386 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001387 }
1388};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001389}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001390
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001391//===----------------------------------------------------------------------===//
1392// -Wthread-safety
1393//===----------------------------------------------------------------------===//
1394namespace clang {
1395namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001396namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001397class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1398 Sema &S;
1399 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001400 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001401
1402 // Helper functions
1403 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001404 // Gracefully handle rare cases when the analysis can't get a more
1405 // precise source location.
1406 if (!Loc.isValid())
1407 Loc = FunLocation;
Richard Smith92286672012-02-03 04:45:26 +00001408 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1409 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001410 }
1411
1412 public:
Richard Smith92286672012-02-03 04:45:26 +00001413 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1414 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001415
1416 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1417 /// We need to output diagnostics produced while iterating through
1418 /// the lockset in deterministic order, so this function orders diagnostics
1419 /// and outputs them.
1420 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001421 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001422 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001423 I != E; ++I) {
1424 S.Diag(I->first.first, I->first.second);
1425 const OptionalNotes &Notes = I->second;
1426 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1427 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1428 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001429 }
1430
Craig Toppere14c0f82014-03-12 04:55:44 +00001431 void handleInvalidLockExp(SourceLocation Loc) override {
Richard Smith92286672012-02-03 04:45:26 +00001432 PartialDiagnosticAt Warning(Loc,
1433 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1434 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001435 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001436 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) override {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001437 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1438 }
1439
Craig Toppere14c0f82014-03-12 04:55:44 +00001440 void handleDoubleLock(Name LockName, SourceLocation Loc) override {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001441 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1442 }
1443
Richard Smith92286672012-02-03 04:45:26 +00001444 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1445 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001446 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001447 unsigned DiagID = 0;
1448 switch (LEK) {
1449 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001450 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001451 break;
1452 case LEK_LockedSomeLoopIterations:
1453 DiagID = diag::warn_expecting_lock_held_on_loop;
1454 break;
1455 case LEK_LockedAtEndOfFunction:
1456 DiagID = diag::warn_no_unlock;
1457 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001458 case LEK_NotLockedAtEndOfFunction:
1459 DiagID = diag::warn_expecting_locked;
1460 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001461 }
Richard Smith92286672012-02-03 04:45:26 +00001462 if (LocEndOfScope.isInvalid())
1463 LocEndOfScope = FunEndLocation;
1464
1465 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001466 if (LocLocked.isValid()) {
1467 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1468 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1469 return;
1470 }
1471 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001472 }
1473
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001474
1475 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001476 SourceLocation Loc2) override {
Richard Smith92286672012-02-03 04:45:26 +00001477 PartialDiagnosticAt Warning(
1478 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1479 PartialDiagnosticAt Note(
1480 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1481 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001482 }
1483
1484 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
Craig Toppere14c0f82014-03-12 04:55:44 +00001485 AccessKind AK, SourceLocation Loc) override {
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001486 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1487 && "Only works for variables");
1488 unsigned DiagID = POK == POK_VarAccess?
1489 diag::warn_variable_requires_any_lock:
1490 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001491 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001492 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001493 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001494 }
1495
1496 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001497 Name LockName, LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001498 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001499 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001500 if (PossibleMatch) {
1501 switch (POK) {
1502 case POK_VarAccess:
1503 DiagID = diag::warn_variable_requires_lock_precise;
1504 break;
1505 case POK_VarDereference:
1506 DiagID = diag::warn_var_deref_requires_lock_precise;
1507 break;
1508 case POK_FunctionCall:
1509 DiagID = diag::warn_fun_requires_lock_precise;
1510 break;
1511 }
1512 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001513 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001514 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1515 << *PossibleMatch);
1516 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1517 } else {
1518 switch (POK) {
1519 case POK_VarAccess:
1520 DiagID = diag::warn_variable_requires_lock;
1521 break;
1522 case POK_VarDereference:
1523 DiagID = diag::warn_var_deref_requires_lock;
1524 break;
1525 case POK_FunctionCall:
1526 DiagID = diag::warn_fun_requires_lock;
1527 break;
1528 }
1529 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001530 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001531 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001532 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001533 }
1534
Craig Toppere14c0f82014-03-12 04:55:44 +00001535 void handleFunExcludesLock(Name FunName, Name LockName,
1536 SourceLocation Loc) override {
Richard Smith92286672012-02-03 04:45:26 +00001537 PartialDiagnosticAt Warning(Loc,
1538 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1539 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001540 }
1541};
1542}
1543}
David Blaikie68e081d2011-12-20 02:48:34 +00001544}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001545
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001546//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001547// -Wconsumed
1548//===----------------------------------------------------------------------===//
1549
1550namespace clang {
1551namespace consumed {
1552namespace {
1553class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1554
1555 Sema &S;
1556 DiagList Warnings;
1557
1558public:
1559
1560 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001561
1562 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001563 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1564
1565 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1566 I != E; ++I) {
1567
1568 const OptionalNotes &Notes = I->second;
1569 S.Diag(I->first.first, I->first.second);
1570
1571 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1572 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1573 }
1574 }
1575 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001576
1577 void warnLoopStateMismatch(SourceLocation Loc,
1578 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001579 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1580 VariableName);
1581
1582 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1583 }
1584
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001585 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1586 StringRef VariableName,
1587 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001588 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001589
1590 PartialDiagnosticAt Warning(Loc, S.PDiag(
1591 diag::warn_param_return_typestate_mismatch) << VariableName <<
1592 ExpectedState << ObservedState);
1593
1594 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1595 }
1596
DeLesley Hutchins69391772013-10-17 23:23:53 +00001597 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001598 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001599
1600 PartialDiagnosticAt Warning(Loc, S.PDiag(
1601 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1602
1603 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1604 }
1605
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001606 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001607 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001608 PartialDiagnosticAt Warning(Loc, S.PDiag(
1609 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1610
1611 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1612 }
1613
1614 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001615 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001616
1617 PartialDiagnosticAt Warning(Loc, S.PDiag(
1618 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1619
1620 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1621 }
1622
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001623 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001624 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001625
1626 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001627 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001628
1629 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1630 }
1631
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001632 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001633 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001634
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001635 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1636 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001637
1638 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1639 }
1640};
1641}}}
1642
1643//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001644// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1645// warnings on a function, method, or block.
1646//===----------------------------------------------------------------------===//
1647
Ted Kremenek0b405322010-03-23 00:13:23 +00001648clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1649 enableCheckFallThrough = 1;
1650 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001651 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001652 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001653}
1654
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001655clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1656 : S(s),
1657 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001658 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001659 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001660 MaxCFGBlocksPerFunction(0),
1661 NumUninitAnalysisFunctions(0),
1662 NumUninitAnalysisVariables(0),
1663 MaxUninitAnalysisVariablesPerFunction(0),
1664 NumUninitAnalysisBlockVisits(0),
1665 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikie9c902b52011-09-25 23:23:43 +00001666 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenek0b405322010-03-23 00:13:23 +00001667 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001668 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001669 DiagnosticsEngine::Ignored);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001670 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1671 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikie9c902b52011-09-25 23:23:43 +00001672 DiagnosticsEngine::Ignored);
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001673 DefaultPolicy.enableConsumedAnalysis = (unsigned)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001674 (D.getDiagnosticLevel(diag::warn_use_in_invalid_state, SourceLocation()) !=
DeLesley Hutchinsc2ecf0d2013-08-22 20:44:47 +00001675 DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +00001676}
1677
Ted Kremenek3427fac2011-02-23 01:52:04 +00001678static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001679 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001680 i = fscope->PossiblyUnreachableDiags.begin(),
1681 e = fscope->PossiblyUnreachableDiags.end();
1682 i != e; ++i) {
1683 const sema::PossiblyUnreachableDiag &D = *i;
1684 S.Diag(D.Loc, D.PD);
1685 }
1686}
1687
Ted Kremenek0b405322010-03-23 00:13:23 +00001688void clang::sema::
1689AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001690 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001691 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001692
Ted Kremenek918fe842010-03-20 21:06:02 +00001693 // We avoid doing analysis-based warnings when there are errors for
1694 // two reasons:
1695 // (1) The CFGs often can't be constructed (if the body is invalid), so
1696 // don't bother trying.
1697 // (2) The code already has problems; running the analysis just takes more
1698 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001699 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001700
Ted Kremenek0b405322010-03-23 00:13:23 +00001701 // Do not do any analysis for declarations in system headers if we are
1702 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001703 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001704 S.SourceMgr.isInSystemHeader(D->getLocation()))
1705 return;
1706
John McCall1d570a72010-08-25 05:56:39 +00001707 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001708 if (cast<DeclContext>(D)->isDependentContext())
1709 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001710
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001711 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001712 // Flush out any possibly unreachable diagnostics.
1713 flushDiagnostics(S, fscope);
1714 return;
1715 }
1716
Ted Kremenek918fe842010-03-20 21:06:02 +00001717 const Stmt *Body = D->getBody();
1718 assert(Body);
1719
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001720 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001721 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001722
Ted Kremenek918fe842010-03-20 21:06:02 +00001723 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001724 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001725 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1726 AC.getCFGBuildOptions().AddEHEdges = false;
1727 AC.getCFGBuildOptions().AddInitializers = true;
1728 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001729 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001730 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001731
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001732 // Force that certain expressions appear as CFGElements in the CFG. This
1733 // is used to speed up various analyses.
1734 // FIXME: This isn't the right factoring. This is here for initial
1735 // prototyping, but we need a way for analyses to say what expressions they
1736 // expect to always be CFGElements and then fill in the BuildOptions
1737 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001738 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1739 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001740 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001741 AC.getCFGBuildOptions().setAllAlwaysAdd();
1742 }
1743 else {
1744 AC.getCFGBuildOptions()
1745 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001746 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001747 .setAlwaysAdd(Stmt::BlockExprClass)
1748 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1749 .setAlwaysAdd(Stmt::DeclRefExprClass)
1750 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001751 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1752 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001753 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001754
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001755
Ted Kremenek3427fac2011-02-23 01:52:04 +00001756 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001757 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001758 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001759
1760 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001761 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001762 i = fscope->PossiblyUnreachableDiags.begin(),
1763 e = fscope->PossiblyUnreachableDiags.end();
1764 i != e; ++i) {
1765 if (const Stmt *stmt = i->stmt)
1766 AC.registerForcedBlockExpression(stmt);
1767 }
1768
1769 if (AC.getCFG()) {
1770 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001771 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001772 i = fscope->PossiblyUnreachableDiags.begin(),
1773 e = fscope->PossiblyUnreachableDiags.end();
1774 i != e; ++i)
1775 {
1776 const sema::PossiblyUnreachableDiag &D = *i;
1777 bool processed = false;
1778 if (const Stmt *stmt = i->stmt) {
1779 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001780 CFGReverseBlockReachabilityAnalysis *cra =
1781 AC.getCFGReachablityAnalysis();
1782 // FIXME: We should be able to assert that block is non-null, but
1783 // the CFG analysis can skip potentially-evaluated expressions in
1784 // edge cases; see test/Sema/vla-2.c.
1785 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001786 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001787 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001788 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001789 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001790 }
1791 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001792 if (!processed) {
1793 // Emit the warning anyway if we cannot map to a basic block.
1794 S.Diag(D.Loc, D.PD);
1795 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001796 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001797 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001798
1799 if (!analyzed)
1800 flushDiagnostics(S, fscope);
1801 }
1802
1803
Ted Kremenek918fe842010-03-20 21:06:02 +00001804 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001805 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001806 const CheckFallThroughDiagnostics &CD =
1807 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001808 : (isa<CXXMethodDecl>(D) &&
1809 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1810 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1811 ? CheckFallThroughDiagnostics::MakeForLambda()
1812 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001813 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001814 }
1815
1816 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001817 if (P.enableCheckUnreachable) {
1818 // Only check for unreachable code on non-template instantiations.
1819 // Different template instantiations can effectively change the control-flow
1820 // and it is very difficult to prove that a snippet of code in a template
1821 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001822 bool isTemplateInstantiation = false;
1823 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1824 isTemplateInstantiation = Function->isTemplateInstantiation();
1825 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001826 CheckUnreachable(S, AC);
1827 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001828
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001829 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001830 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001831 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001832 SourceLocation FEL = AC.getDecl()->getLocEnd();
1833 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001834 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1835 != DiagnosticsEngine::Ignored)
1836 Reporter.setIssueBetaWarnings(true);
1837
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001838 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1839 Reporter.emitDiagnostics();
1840 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001841
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001842 // Check for violations of consumed properties.
1843 if (P.enableConsumedAnalysis) {
1844 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001845 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001846 Analyzer.run(AC);
1847 }
1848
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001849 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001850 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001851 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1852 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001853 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001854 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001855 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001856 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001857 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001858 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001859 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001860 reporter, stats);
1861
1862 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1863 ++NumUninitAnalysisFunctions;
1864 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1865 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1866 MaxUninitAnalysisVariablesPerFunction =
1867 std::max(MaxUninitAnalysisVariablesPerFunction,
1868 stats.NumVariablesAnalyzed);
1869 MaxUninitAnalysisBlockVisitsPerFunction =
1870 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1871 stats.NumBlockVisits);
1872 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001873 }
1874 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001875
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001876 bool FallThroughDiagFull =
1877 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1878 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001879 bool FallThroughDiagPerFunction =
1880 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001881 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001882 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001883 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001884 }
1885
Jordan Rosed3934582012-09-28 22:21:30 +00001886 if (S.getLangOpts().ObjCARCWeak &&
1887 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1888 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001889 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001890
Richard Trieu2f024f42013-12-21 02:33:43 +00001891
1892 // Check for infinite self-recursion in functions
1893 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1894 D->getLocStart())
1895 != DiagnosticsEngine::Ignored) {
1896 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1897 checkRecursiveFunction(S, FD, Body, AC);
1898 }
1899 }
1900
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001901 // Collect statistics about the CFG if it was built.
1902 if (S.CollectStats && AC.isCFGBuilt()) {
1903 ++NumFunctionsAnalyzed;
1904 if (CFG *cfg = AC.getCFG()) {
1905 // If we successfully built a CFG for this context, record some more
1906 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00001907 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001908 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00001909 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001910 } else {
1911 ++NumFunctionsWithBadCFGs;
1912 }
1913 }
1914}
1915
1916void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1917 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1918
1919 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1920 unsigned AvgCFGBlocksPerFunction =
1921 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1922 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1923 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1924 << " " << NumCFGBlocks << " CFG blocks built.\n"
1925 << " " << AvgCFGBlocksPerFunction
1926 << " average CFG blocks per function.\n"
1927 << " " << MaxCFGBlocksPerFunction
1928 << " max CFG blocks per function.\n";
1929
1930 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1931 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1932 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1933 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1934 llvm::errs() << NumUninitAnalysisFunctions
1935 << " functions analyzed for uninitialiazed variables\n"
1936 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1937 << " " << AvgUninitVariablesPerFunction
1938 << " average variables per function.\n"
1939 << " " << MaxUninitAnalysisVariablesPerFunction
1940 << " max variables per function.\n"
1941 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1942 << " " << AvgUninitBlockVisitsPerFunction
1943 << " average block visits per function.\n"
1944 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1945 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00001946}