blob: ec500a06c322aa4fdaf773de03aec0b48a150486 [file] [log] [blame]
Ted Kremenekdbdbaaf2010-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 Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000018#include "clang/Sema/ScopeInfo.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000019#include "clang/Basic/SourceManager.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000020#include "clang/Basic/SourceLocation.h"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000021#include "clang/Lex/Preprocessor.h"
Richard Smithbdb97ff2012-05-26 06:20:46 +000022#include "clang/Lex/Lexer.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000025#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/StmtObjC.h"
28#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000030#include "clang/AST/StmtVisitor.h"
Richard Smithe0d3b4c2012-05-03 18:27:39 +000031#include "clang/AST/RecursiveASTVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
34#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000035#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000036#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000037#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000038#include "clang/Analysis/Analyses/UninitializedValues.h"
Alexander Kornienko66da0ab2012-09-28 22:24:03 +000039#include "llvm/ADT/ArrayRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000040#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000041#include "llvm/ADT/FoldingSet.h"
42#include "llvm/ADT/ImmutableMap.h"
43#include "llvm/ADT/PostOrderIterator.h"
44#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000045#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000046#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000047#include <algorithm>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000048#include <iterator>
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000049#include <vector>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000050#include <deque>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000051
52using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Unreachable code analysis.
56//===----------------------------------------------------------------------===//
57
58namespace {
59 class UnreachableCodeHandler : public reachable_code::Callback {
60 Sema &S;
61 public:
62 UnreachableCodeHandler(Sema &s) : S(s) {}
63
64 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
65 S.Diag(L, diag::warn_unreachable) << R1 << R2;
66 }
67 };
68}
69
70/// CheckUnreachable - Check for unreachable code.
Ted Kremenek1d26f482011-10-24 01:32:45 +000071static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000072 UnreachableCodeHandler UC(S);
73 reachable_code::FindUnreachableCode(AC, UC);
74}
75
76//===----------------------------------------------------------------------===//
77// Check for missing return value.
78//===----------------------------------------------------------------------===//
79
John McCall16565aa2010-05-16 09:34:11 +000080enum ControlFlowKind {
81 UnknownFallThrough,
82 NeverFallThrough,
83 MaybeFallThrough,
84 AlwaysFallThrough,
85 NeverFallThroughOrReturn
86};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000087
88/// CheckFallThrough - Check that we don't fall off the end of a
89/// Statement that should return a value.
90///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000091/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
92/// MaybeFallThrough iff we might or might not fall off the end,
93/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
94/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000095/// statement but we may return. We assume that functions not marked noreturn
96/// will return.
Ted Kremenek1d26f482011-10-24 01:32:45 +000097static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000098 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000099 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000100
101 // The CFG leaves in dead things, and we don't want the dead code paths to
102 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000103 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000104 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000105 live);
106
107 bool AddEHEdges = AC.getAddEHEdges();
108 if (!AddEHEdges && count != cfg->getNumBlockIDs())
109 // When there are things remaining dead, and we didn't add EH edges
110 // from CallExprs to the catch clauses, we have to go back and
111 // mark them as live.
112 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
113 CFGBlock &b = **I;
114 if (!live[b.getBlockID()]) {
115 if (b.pred_begin() == b.pred_end()) {
116 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
117 // When not adding EH edges from calls, catch clauses
118 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000119 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000120 continue;
121 }
122 }
123 }
124
125 // Now we know what is live, we check the live precessors of the exit block
126 // and look for fall through paths, being careful to ignore normal returns,
127 // and exceptional paths.
128 bool HasLiveReturn = false;
129 bool HasFakeEdge = false;
130 bool HasPlainEdge = false;
131 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000132
133 // Ignore default cases that aren't likely to be reachable because all
134 // enums in a switch(X) have explicit case statements.
135 CFGBlock::FilterOptions FO;
136 FO.IgnoreDefaultsWithCoveredEnums = 1;
137
138 for (CFGBlock::filtered_pred_iterator
139 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
140 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000141 if (!live[B.getBlockID()])
142 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000143
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000144 // Skip blocks which contain an element marked as no-return. They don't
145 // represent actually viable edges into the exit block, so mark them as
146 // abnormal.
147 if (B.hasNoReturnElement()) {
148 HasAbnormalEdge = true;
149 continue;
150 }
151
Ted Kremenek5811f592011-01-26 04:49:52 +0000152 // Destructors can appear after the 'return' in the CFG. This is
153 // normal. We need to look pass the destructors for the return
154 // statement (if it exists).
155 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000156
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000157 for ( ; ri != re ; ++ri)
158 if (isa<CFGStmt>(*ri))
Ted Kremenek5811f592011-01-26 04:49:52 +0000159 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000160
Ted Kremenek5811f592011-01-26 04:49:52 +0000161 // No more CFGElements in the block?
162 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000163 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
164 HasAbnormalEdge = true;
165 continue;
166 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000167 // A labeled empty statement, or the entry block...
168 HasPlainEdge = true;
169 continue;
170 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000171
Ted Kremenek5811f592011-01-26 04:49:52 +0000172 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000173 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000174 if (isa<ReturnStmt>(S)) {
175 HasLiveReturn = true;
176 continue;
177 }
178 if (isa<ObjCAtThrowStmt>(S)) {
179 HasFakeEdge = true;
180 continue;
181 }
182 if (isa<CXXThrowExpr>(S)) {
183 HasFakeEdge = true;
184 continue;
185 }
Chad Rosier8cd64b42012-06-11 20:47:18 +0000186 if (isa<MSAsmStmt>(S)) {
187 // TODO: Verify this is correct.
188 HasFakeEdge = true;
189 HasLiveReturn = true;
190 continue;
191 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000192 if (isa<CXXTryStmt>(S)) {
193 HasAbnormalEdge = true;
194 continue;
195 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000196 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
197 == B.succ_end()) {
198 HasAbnormalEdge = true;
199 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000200 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000201
202 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000203 }
204 if (!HasPlainEdge) {
205 if (HasLiveReturn)
206 return NeverFallThrough;
207 return NeverFallThroughOrReturn;
208 }
209 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
210 return MaybeFallThrough;
211 // This says AlwaysFallThrough for calls to functions that are not marked
212 // noreturn, that don't return. If people would like this warning to be more
213 // accurate, such functions should be marked as noreturn.
214 return AlwaysFallThrough;
215}
216
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000217namespace {
218
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000219struct CheckFallThroughDiagnostics {
220 unsigned diag_MaybeFallThrough_HasNoReturn;
221 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
222 unsigned diag_AlwaysFallThrough_HasNoReturn;
223 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
224 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000225 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000226 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000227
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000228 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000229 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000230 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000231 D.diag_MaybeFallThrough_HasNoReturn =
232 diag::warn_falloff_noreturn_function;
233 D.diag_MaybeFallThrough_ReturnsNonVoid =
234 diag::warn_maybe_falloff_nonvoid_function;
235 D.diag_AlwaysFallThrough_HasNoReturn =
236 diag::warn_falloff_noreturn_function;
237 D.diag_AlwaysFallThrough_ReturnsNonVoid =
238 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000239
240 // Don't suggest that virtual functions be marked "noreturn", since they
241 // might be overridden by non-noreturn functions.
242 bool isVirtualMethod = false;
243 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
244 isVirtualMethod = Method->isVirtual();
245
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000246 // Don't suggest that template instantiations be marked "noreturn"
247 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000248 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
249 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000250
251 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000252 D.diag_NeverFallThroughOrReturn =
253 diag::warn_suggest_noreturn_function;
254 else
255 D.diag_NeverFallThroughOrReturn = 0;
256
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000257 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000258 return D;
259 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000260
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000261 static CheckFallThroughDiagnostics MakeForBlock() {
262 CheckFallThroughDiagnostics D;
263 D.diag_MaybeFallThrough_HasNoReturn =
264 diag::err_noreturn_block_has_return_expr;
265 D.diag_MaybeFallThrough_ReturnsNonVoid =
266 diag::err_maybe_falloff_nonvoid_block;
267 D.diag_AlwaysFallThrough_HasNoReturn =
268 diag::err_noreturn_block_has_return_expr;
269 D.diag_AlwaysFallThrough_ReturnsNonVoid =
270 diag::err_falloff_nonvoid_block;
271 D.diag_NeverFallThroughOrReturn =
272 diag::warn_suggest_noreturn_block;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000273 D.funMode = Block;
274 return D;
275 }
276
277 static CheckFallThroughDiagnostics MakeForLambda() {
278 CheckFallThroughDiagnostics D;
279 D.diag_MaybeFallThrough_HasNoReturn =
280 diag::err_noreturn_lambda_has_return_expr;
281 D.diag_MaybeFallThrough_ReturnsNonVoid =
282 diag::warn_maybe_falloff_nonvoid_lambda;
283 D.diag_AlwaysFallThrough_HasNoReturn =
284 diag::err_noreturn_lambda_has_return_expr;
285 D.diag_AlwaysFallThrough_ReturnsNonVoid =
286 diag::warn_falloff_nonvoid_lambda;
287 D.diag_NeverFallThroughOrReturn = 0;
288 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000289 return D;
290 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000291
David Blaikied6471f72011-09-25 23:23:43 +0000292 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000293 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000294 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000295 return (ReturnsVoid ||
296 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000297 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000298 && (!HasNoReturn ||
299 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000300 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000301 && (!ReturnsVoid ||
302 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000303 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000304 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000305
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000306 // For blocks / lambdas.
307 return ReturnsVoid && !HasNoReturn
308 && ((funMode == Lambda) ||
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000309 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000310 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000311 }
312};
313
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000314}
315
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000316/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
317/// function that should return a value. Check that we don't fall off the end
318/// of a noreturn function. We assume that functions and blocks not marked
319/// noreturn will return.
320static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000321 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000322 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000323 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000324
325 bool ReturnsVoid = false;
326 bool HasNoReturn = false;
327
328 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
329 ReturnsVoid = FD->getResultType()->isVoidType();
330 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000331 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000332 }
333 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
334 ReturnsVoid = MD->getResultType()->isVoidType();
335 HasNoReturn = MD->hasAttr<NoReturnAttr>();
336 }
337 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000338 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000339 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000340 BlockTy->getPointeeType()->getAs<FunctionType>()) {
341 if (FT->getResultType()->isVoidType())
342 ReturnsVoid = true;
343 if (FT->getNoReturnAttr())
344 HasNoReturn = true;
345 }
346 }
347
David Blaikied6471f72011-09-25 23:23:43 +0000348 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000349
350 // Short circuit for compilation speed.
351 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
352 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000353
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000354 // FIXME: Function try block
355 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
356 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000357 case UnknownFallThrough:
358 break;
359
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000360 case MaybeFallThrough:
361 if (HasNoReturn)
362 S.Diag(Compound->getRBracLoc(),
363 CD.diag_MaybeFallThrough_HasNoReturn);
364 else if (!ReturnsVoid)
365 S.Diag(Compound->getRBracLoc(),
366 CD.diag_MaybeFallThrough_ReturnsNonVoid);
367 break;
368 case AlwaysFallThrough:
369 if (HasNoReturn)
370 S.Diag(Compound->getRBracLoc(),
371 CD.diag_AlwaysFallThrough_HasNoReturn);
372 else if (!ReturnsVoid)
373 S.Diag(Compound->getRBracLoc(),
374 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
375 break;
376 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000377 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
378 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
379 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000380 << 0 << FD;
381 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
382 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
383 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000384 } else {
385 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
386 }
387 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000388 break;
389 case NeverFallThrough:
390 break;
391 }
392 }
393}
394
395//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000396// -Wuninitialized
397//===----------------------------------------------------------------------===//
398
Ted Kremenek6f417152011-04-04 20:56:00 +0000399namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000400/// ContainsReference - A visitor class to search for references to
401/// a particular declaration (the needle) within any evaluated component of an
402/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000403class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000404 bool FoundReference;
405 const DeclRefExpr *Needle;
406
Ted Kremenek6f417152011-04-04 20:56:00 +0000407public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000408 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
409 : EvaluatedExprVisitor<ContainsReference>(Context),
410 FoundReference(false), Needle(Needle) {}
411
412 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000413 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000414 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000415 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000416
417 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000418 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000419
420 void VisitDeclRefExpr(DeclRefExpr *E) {
421 if (E == Needle)
422 FoundReference = true;
423 else
424 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000425 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000426
427 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000428};
429}
430
David Blaikie4f4f3492011-09-10 05:35:08 +0000431static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000432 QualType VariableTy = VD->getType().getCanonicalType();
433 if (VariableTy->isBlockPointerType() &&
434 !VD->hasAttr<BlocksAttr>()) {
435 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
436 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
437 return true;
438 }
439
David Blaikie4f4f3492011-09-10 05:35:08 +0000440 // Don't issue a fixit if there is already an initializer.
441 if (VD->getInit())
442 return false;
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000443
David Blaikie4f4f3492011-09-10 05:35:08 +0000444 // Suggest possible initialization (if any).
David Blaikie2c0abf42012-04-30 18:27:22 +0000445 std::string Init = S.getFixItZeroInitializerForType(VariableTy);
446 if (Init.empty())
David Blaikie4f4f3492011-09-10 05:35:08 +0000447 return false;
Richard Trieu7b0a3e32012-05-03 01:09:59 +0000448
449 // Don't suggest a fixit inside macros.
450 if (VD->getLocEnd().isMacroID())
451 return false;
452
Richard Smith7984de32012-01-12 23:53:29 +0000453 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000454
Richard Smith7984de32012-01-12 23:53:29 +0000455 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
456 << FixItHint::CreateInsertion(Loc, Init);
457 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000458}
459
Richard Smithbdb97ff2012-05-26 06:20:46 +0000460/// Create a fixit to remove an if-like statement, on the assumption that its
461/// condition is CondVal.
462static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
463 const Stmt *Else, bool CondVal,
464 FixItHint &Fixit1, FixItHint &Fixit2) {
465 if (CondVal) {
466 // If condition is always true, remove all but the 'then'.
467 Fixit1 = FixItHint::CreateRemoval(
468 CharSourceRange::getCharRange(If->getLocStart(),
469 Then->getLocStart()));
470 if (Else) {
471 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
472 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
473 Fixit2 = FixItHint::CreateRemoval(
474 SourceRange(ElseKwLoc, Else->getLocEnd()));
475 }
476 } else {
477 // If condition is always false, remove all but the 'else'.
478 if (Else)
479 Fixit1 = FixItHint::CreateRemoval(
480 CharSourceRange::getCharRange(If->getLocStart(),
481 Else->getLocStart()));
482 else
483 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
484 }
485}
486
487/// DiagUninitUse -- Helper function to produce a diagnostic for an
488/// uninitialized use of a variable.
489static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
490 bool IsCapturedByBlock) {
491 bool Diagnosed = false;
492
493 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith2815e1a2012-05-25 02:17:09 +0000494 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
495 I != E; ++I) {
Richard Smithbdb97ff2012-05-26 06:20:46 +0000496 assert(Use.getKind() == UninitUse::Sometimes);
497
498 const Expr *User = Use.getUser();
Richard Smith2815e1a2012-05-25 02:17:09 +0000499 const Stmt *Term = I->Terminator;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000500
501 // Information used when building the diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000502 unsigned DiagKind;
Richard Smith2815e1a2012-05-25 02:17:09 +0000503 const char *Str;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000504 SourceRange Range;
505
506 // FixIts to suppress the diagnosic by removing the dead condition.
507 // For all binary terminators, branch 0 is taken if the condition is true,
508 // and branch 1 is taken if the condition is false.
509 int RemoveDiagKind = -1;
510 const char *FixitStr =
511 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
512 : (I->Output ? "1" : "0");
513 FixItHint Fixit1, Fixit2;
514
Richard Smith2815e1a2012-05-25 02:17:09 +0000515 switch (Term->getStmtClass()) {
516 default:
Richard Smithbdb97ff2012-05-26 06:20:46 +0000517 // Don't know how to report this. Just fall back to 'may be used
518 // uninitialized'. This happens for range-based for, which the user
519 // can't explicitly fix.
520 // FIXME: This also happens if the first use of a variable is always
521 // uninitialized, eg "for (int n; n < 10; ++n)". We should report that
522 // with the 'is uninitialized' diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000523 continue;
524
525 // "condition is true / condition is false".
Richard Smithbdb97ff2012-05-26 06:20:46 +0000526 case Stmt::IfStmtClass: {
527 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000528 DiagKind = 0;
529 Str = "if";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000530 Range = IS->getCond()->getSourceRange();
531 RemoveDiagKind = 0;
532 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
533 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000534 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000535 }
536 case Stmt::ConditionalOperatorClass: {
537 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000538 DiagKind = 0;
539 Str = "?:";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000540 Range = CO->getCond()->getSourceRange();
541 RemoveDiagKind = 0;
542 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
543 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000544 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000545 }
Richard Smith2815e1a2012-05-25 02:17:09 +0000546 case Stmt::BinaryOperatorClass: {
547 const BinaryOperator *BO = cast<BinaryOperator>(Term);
548 if (!BO->isLogicalOp())
549 continue;
550 DiagKind = 0;
551 Str = BO->getOpcodeStr();
552 Range = BO->getLHS()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000553 RemoveDiagKind = 0;
554 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
555 (BO->getOpcode() == BO_LOr && !I->Output))
556 // true && y -> y, false || y -> y.
557 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
558 BO->getOperatorLoc()));
559 else
560 // false && y -> false, true || y -> true.
561 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000562 break;
563 }
564
565 // "loop is entered / loop is exited".
566 case Stmt::WhileStmtClass:
567 DiagKind = 1;
568 Str = "while";
569 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000570 RemoveDiagKind = 1;
571 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000572 break;
573 case Stmt::ForStmtClass:
574 DiagKind = 1;
575 Str = "for";
576 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000577 RemoveDiagKind = 1;
578 if (I->Output)
579 Fixit1 = FixItHint::CreateRemoval(Range);
580 else
581 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000582 break;
583
584 // "condition is true / loop is exited".
585 case Stmt::DoStmtClass:
586 DiagKind = 2;
587 Str = "do";
588 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000589 RemoveDiagKind = 1;
590 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000591 break;
592
593 // "switch case is taken".
594 case Stmt::CaseStmtClass:
595 DiagKind = 3;
596 Str = "case";
597 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
598 break;
599 case Stmt::DefaultStmtClass:
600 DiagKind = 3;
601 Str = "default";
602 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
603 break;
604 }
605
Richard Smithbdb97ff2012-05-26 06:20:46 +0000606 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
607 << VD->getDeclName() << IsCapturedByBlock << DiagKind
608 << Str << I->Output << Range;
609 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
610 << IsCapturedByBlock << User->getSourceRange();
611 if (RemoveDiagKind != -1)
612 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
613 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
614
615 Diagnosed = true;
Richard Smith2815e1a2012-05-25 02:17:09 +0000616 }
Richard Smithbdb97ff2012-05-26 06:20:46 +0000617
618 if (!Diagnosed)
619 S.Diag(Use.getUser()->getLocStart(),
620 Use.getKind() == UninitUse::Always ? diag::warn_uninit_var
621 : diag::warn_maybe_uninit_var)
622 << VD->getDeclName() << IsCapturedByBlock
623 << Use.getUser()->getSourceRange();
Richard Smith2815e1a2012-05-25 02:17:09 +0000624}
625
Chandler Carruth262d50e2011-04-05 18:27:05 +0000626/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
627/// uninitialized variable. This manages the different forms of diagnostic
628/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith2815e1a2012-05-25 02:17:09 +0000629/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruth262d50e2011-04-05 18:27:05 +0000630/// false.
631static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith2815e1a2012-05-25 02:17:09 +0000632 const UninitUse &Use,
Ted Kremenek9e761722011-10-13 18:50:06 +0000633 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000634
Richard Smith2815e1a2012-05-25 02:17:09 +0000635 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieuf6278e52012-05-09 21:08:22 +0000636 // Inspect the initializer of the variable declaration which is
637 // being referenced prior to its initialization. We emit
638 // specialized diagnostics for self-initialization, and we
639 // specifically avoid warning about self references which take the
640 // form of:
641 //
642 // int x = x;
643 //
644 // This is used to indicate to GCC that 'x' is intentionally left
645 // uninitialized. Proven code paths which access 'x' in
646 // an uninitialized state after this will still warn.
647 if (const Expr *Initializer = VD->getInit()) {
648 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
649 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000650
Richard Trieuf6278e52012-05-09 21:08:22 +0000651 ContainsReference CR(S.Context, DRE);
652 CR.Visit(const_cast<Expr*>(Initializer));
653 if (CR.doesContainReference()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000654 S.Diag(DRE->getLocStart(),
655 diag::warn_uninit_self_reference_in_init)
Richard Trieuf6278e52012-05-09 21:08:22 +0000656 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
657 return true;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000658 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000659 }
Richard Trieuf6278e52012-05-09 21:08:22 +0000660
Richard Smithbdb97ff2012-05-26 06:20:46 +0000661 DiagUninitUse(S, VD, Use, false);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000662 } else {
Richard Smith2815e1a2012-05-25 02:17:09 +0000663 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smithbdb97ff2012-05-26 06:20:46 +0000664 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
665 S.Diag(BE->getLocStart(),
666 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000667 << VD->getDeclName();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000668 else
669 DiagUninitUse(S, VD, Use, true);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000670 }
671
672 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000673 // the initializer of that declaration & we didn't already suggest
674 // an initialization fixit.
Richard Trieuf6278e52012-05-09 21:08:22 +0000675 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000676 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
677 << VD->getDeclName();
678
Chandler Carruth262d50e2011-04-05 18:27:05 +0000679 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000680}
681
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000682/// \brief Stores token information for comparing actual tokens with
683/// predefined values. Only handles simple tokens and identifiers.
684class TokenValue {
685 tok::TokenKind Kind;
686 IdentifierInfo *II;
687
688public:
689 TokenValue(tok::TokenKind Kind) : Kind(Kind), II(0) {
690 assert(Kind != tok::raw_identifier && "Raw identifiers are not supported.");
691 assert(Kind != tok::identifier &&
692 "Identifiers should be created by TokenValue(IdentifierInfo *)");
693 assert(!tok::isLiteral(Kind) && "Literals are not supported.");
694 assert(!tok::isAnnotation(Kind) && "Annotations are not supported.");
695 }
696 TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {}
697 bool operator==(const Token &Tok) const {
698 return Tok.getKind() == Kind &&
699 (!II || II == Tok.getIdentifierInfo());
700 }
701};
702
703/// \brief Compares macro tokens with a specified token value sequence.
704static bool MacroDefinitionEquals(const MacroInfo *MI,
705 llvm::ArrayRef<TokenValue> Tokens) {
706 return Tokens.size() == MI->getNumTokens() &&
707 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
708}
709
710static std::string GetSuitableSpelling(Preprocessor &PP, SourceLocation L,
711 llvm::ArrayRef<TokenValue> Tokens,
712 const char *Spelling) {
713 SourceManager &SM = PP.getSourceManager();
714 SourceLocation BestLocation;
715 std::string BestSpelling = Spelling;
716 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
717 I != E; ++I) {
718 if (!I->second->isObjectLike())
719 continue;
720 const MacroInfo *MI = I->second->findDefinitionAtLoc(L, SM);
721 if (!MI)
722 continue;
723 if (!MacroDefinitionEquals(MI, Tokens))
724 continue;
725 SourceLocation Location = I->second->getDefinitionLoc();
726 // Choose the macro defined latest.
727 if (BestLocation.isInvalid() ||
728 (Location.isValid() &&
729 SM.isBeforeInTranslationUnit(BestLocation, Location))) {
730 BestLocation = Location;
731 BestSpelling = I->first->getName();
732 }
733 }
734 return BestSpelling;
735}
736
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000737namespace {
738 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
739 public:
740 FallthroughMapper(Sema &S)
741 : FoundSwitchStatements(false),
742 S(S) {
743 }
744
745 bool foundSwitchStatements() const { return FoundSwitchStatements; }
746
747 void markFallthroughVisited(const AttributedStmt *Stmt) {
748 bool Found = FallthroughStmts.erase(Stmt);
749 assert(Found);
Kaelyn Uhrain3bb29942012-05-03 19:46:38 +0000750 (void)Found;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000751 }
752
753 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
754
755 const AttrStmts &getFallthroughStmts() const {
756 return FallthroughStmts;
757 }
758
759 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
760 int UnannotatedCnt = 0;
761 AnnotatedCnt = 0;
762
763 std::deque<const CFGBlock*> BlockQueue;
764
765 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
766
767 while (!BlockQueue.empty()) {
768 const CFGBlock *P = BlockQueue.front();
769 BlockQueue.pop_front();
770
771 const Stmt *Term = P->getTerminator();
772 if (Term && isa<SwitchStmt>(Term))
773 continue; // Switch statement, good.
774
775 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
776 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
777 continue; // Previous case label has no statements, good.
778
779 if (P->pred_begin() == P->pred_end()) { // The block is unreachable.
780 // This only catches trivially unreachable blocks.
781 for (CFGBlock::const_iterator ElIt = P->begin(), ElEnd = P->end();
782 ElIt != ElEnd; ++ElIt) {
783 if (const CFGStmt *CS = ElIt->getAs<CFGStmt>()){
784 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
785 S.Diag(AS->getLocStart(),
786 diag::warn_fallthrough_attr_unreachable);
787 markFallthroughVisited(AS);
788 ++AnnotatedCnt;
789 }
790 // Don't care about other unreachable statements.
791 }
792 }
793 // If there are no unreachable statements, this may be a special
794 // case in CFG:
795 // case X: {
796 // A a; // A has a destructor.
797 // break;
798 // }
799 // // <<<< This place is represented by a 'hanging' CFG block.
800 // case Y:
801 continue;
802 }
803
804 const Stmt *LastStmt = getLastStmt(*P);
805 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
806 markFallthroughVisited(AS);
807 ++AnnotatedCnt;
808 continue; // Fallthrough annotation, good.
809 }
810
811 if (!LastStmt) { // This block contains no executable statements.
812 // Traverse its predecessors.
813 std::copy(P->pred_begin(), P->pred_end(),
814 std::back_inserter(BlockQueue));
815 continue;
816 }
817
818 ++UnannotatedCnt;
819 }
820 return !!UnannotatedCnt;
821 }
822
823 // RecursiveASTVisitor setup.
824 bool shouldWalkTypesOfTypeLocs() const { return false; }
825
826 bool VisitAttributedStmt(AttributedStmt *S) {
827 if (asFallThroughAttr(S))
828 FallthroughStmts.insert(S);
829 return true;
830 }
831
832 bool VisitSwitchStmt(SwitchStmt *S) {
833 FoundSwitchStatements = true;
834 return true;
835 }
836
837 private:
838
839 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
840 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
841 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
842 return AS;
843 }
844 return 0;
845 }
846
847 static const Stmt *getLastStmt(const CFGBlock &B) {
848 if (const Stmt *Term = B.getTerminator())
849 return Term;
850 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
851 ElemEnd = B.rend();
852 ElemIt != ElemEnd; ++ElemIt) {
853 if (const CFGStmt *CS = ElemIt->getAs<CFGStmt>())
854 return CS->getStmt();
855 }
856 // Workaround to detect a statement thrown out by CFGBuilder:
857 // case X: {} case Y:
858 // case X: ; case Y:
859 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
860 if (!isa<SwitchCase>(SW->getSubStmt()))
861 return SW->getSubStmt();
862
863 return 0;
864 }
865
866 bool FoundSwitchStatements;
867 AttrStmts FallthroughStmts;
868 Sema &S;
869 };
870}
871
Alexander Kornienko19736342012-06-02 01:01:07 +0000872static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Sean Huntc2f51cf2012-06-15 21:22:05 +0000873 bool PerFunction) {
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000874 FallthroughMapper FM(S);
875 FM.TraverseStmt(AC.getBody());
876
877 if (!FM.foundSwitchStatements())
878 return;
879
Sean Huntc2f51cf2012-06-15 21:22:05 +0000880 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko19736342012-06-02 01:01:07 +0000881 return;
882
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000883 CFG *Cfg = AC.getCFG();
884
885 if (!Cfg)
886 return;
887
888 int AnnotatedCnt;
889
890 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
891 const CFGBlock &B = **I;
892 const Stmt *Label = B.getLabel();
893
894 if (!Label || !isa<SwitchCase>(Label))
895 continue;
896
897 if (!FM.checkFallThroughIntoBlock(B, AnnotatedCnt))
898 continue;
899
Alexander Kornienko19736342012-06-02 01:01:07 +0000900 S.Diag(Label->getLocStart(),
Sean Huntc2f51cf2012-06-15 21:22:05 +0000901 PerFunction ? diag::warn_unannotated_fallthrough_per_function
902 : diag::warn_unannotated_fallthrough);
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000903
904 if (!AnnotatedCnt) {
905 SourceLocation L = Label->getLocStart();
906 if (L.isMacroID())
907 continue;
908 if (S.getLangOpts().CPlusPlus0x) {
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000909 const Stmt *Term = B.getTerminator();
910 if (!(B.empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000911 Preprocessor &PP = S.getPreprocessor();
912 TokenValue Tokens[] = {
913 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
914 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
915 tok::r_square, tok::r_square
916 };
917 std::string AnnotationSpelling = GetSuitableSpelling(
918 PP, L, Tokens, "[[clang::fallthrough]]");
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000919 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000920 AnnotationSpelling <<
921 FixItHint::CreateInsertion(L, AnnotationSpelling + "; ");
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000922 }
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000923 }
924 S.Diag(L, diag::note_insert_break_fixit) <<
925 FixItHint::CreateInsertion(L, "break; ");
926 }
927 }
928
929 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
930 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
931 E = Fallthroughs.end();
932 I != E; ++I) {
933 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
934 }
935
936}
937
Ted Kremenek610068c2011-01-15 02:58:47 +0000938namespace {
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000939 typedef std::pair<const Stmt *,
940 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
941 StmtUsesPair;
942}
943
944template<>
945class BeforeThanCompare<StmtUsesPair> {
946 const SourceManager &SM;
947
948public:
949 explicit BeforeThanCompare(const SourceManager &SM) : SM(SM) { }
950
951 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
952 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
953 RHS.first->getLocStart());
954 }
955};
956
957
958static void diagnoseRepeatedUseOfWeak(Sema &S,
959 const sema::FunctionScopeInfo *CurFn,
960 const Decl *D) {
961 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
962 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
963 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
964
965 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
966
967 // Extract all weak objects that are referenced more than once.
968 SmallVector<StmtUsesPair, 8> UsesByStmt;
969 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
970 I != E; ++I) {
971 const WeakUseVector &Uses = I->second;
972 if (Uses.size() <= 1)
973 continue;
974
975 // Find the first read of the weak object.
976 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
977 for ( ; UI != UE; ++UI) {
978 if (UI->isUnsafe())
979 break;
980 }
981
982 // If there were only writes to this object, don't warn.
983 if (UI == UE)
984 continue;
985
986 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
987 }
988
989 if (UsesByStmt.empty())
990 return;
991
992 // Sort by first use so that we emit the warnings in a deterministic order.
993 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
994 BeforeThanCompare<StmtUsesPair>(S.getSourceManager()));
995
996 // Classify the current code body for better warning text.
997 // This enum should stay in sync with the cases in
998 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
999 // FIXME: Should we use a common classification enum and the same set of
1000 // possibilities all throughout Sema?
1001 enum {
1002 Function,
1003 Method,
1004 Block,
1005 Lambda
1006 } FunctionKind;
1007
1008 if (isa<sema::BlockScopeInfo>(CurFn))
1009 FunctionKind = Block;
1010 else if (isa<sema::LambdaScopeInfo>(CurFn))
1011 FunctionKind = Lambda;
1012 else if (isa<ObjCMethodDecl>(D))
1013 FunctionKind = Method;
1014 else
1015 FunctionKind = Function;
1016
1017 // Iterate through the sorted problems and emit warnings for each.
1018 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1019 E = UsesByStmt.end();
1020 I != E; ++I) {
1021 const Stmt *FirstRead = I->first;
1022 const WeakObjectProfileTy &Key = I->second->first;
1023 const WeakUseVector &Uses = I->second->second;
1024
Jordan Rose7a270482012-09-28 22:21:35 +00001025 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1026 // may not contain enough information to determine that these are different
1027 // properties. We can only be 100% sure of a repeated use in certain cases,
1028 // and we adjust the diagnostic kind accordingly so that the less certain
1029 // case can be turned off if it is too noisy.
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001030 unsigned DiagKind;
1031 if (Key.isExactProfile())
1032 DiagKind = diag::warn_arc_repeated_use_of_weak;
1033 else
1034 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1035
Jordan Rose7a270482012-09-28 22:21:35 +00001036 // Classify the weak object being accessed for better warning text.
1037 // This enum should stay in sync with the cases in
1038 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1039 enum {
1040 Variable,
1041 Property,
1042 ImplicitProperty,
1043 Ivar
1044 } ObjectKind;
1045
1046 const NamedDecl *D = Key.getProperty();
1047 if (isa<VarDecl>(D))
1048 ObjectKind = Variable;
1049 else if (isa<ObjCPropertyDecl>(D))
1050 ObjectKind = Property;
1051 else if (isa<ObjCMethodDecl>(D))
1052 ObjectKind = ImplicitProperty;
1053 else if (isa<ObjCIvarDecl>(D))
1054 ObjectKind = Ivar;
1055 else
1056 llvm_unreachable("Unexpected weak object kind!");
1057
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001058 // Show the first time the object was read.
1059 S.Diag(FirstRead->getLocStart(), DiagKind)
Jordan Rose7a270482012-09-28 22:21:35 +00001060 << ObjectKind << D << FunctionKind
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001061 << FirstRead->getSourceRange();
1062
1063 // Print all the other accesses as notes.
1064 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1065 UI != UE; ++UI) {
1066 if (UI->getUseExpr() == FirstRead)
1067 continue;
1068 S.Diag(UI->getUseExpr()->getLocStart(),
1069 diag::note_arc_weak_also_accessed_here)
1070 << UI->getUseExpr()->getSourceRange();
1071 }
1072 }
1073}
1074
1075
1076namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001077struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +00001078 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001079 // Prefer a more confident report over a less confident one.
1080 if (a.getKind() != b.getKind())
1081 return a.getKind() > b.getKind();
1082 SourceLocation aLoc = a.getUser()->getLocStart();
1083 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001084 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1085 }
1086};
1087
Ted Kremenek610068c2011-01-15 02:58:47 +00001088class UninitValsDiagReporter : public UninitVariablesHandler {
1089 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001090 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek9e761722011-10-13 18:50:06 +00001091 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001092 UsesMap *uses;
1093
Ted Kremenek610068c2011-01-15 02:58:47 +00001094public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001095 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1096 ~UninitValsDiagReporter() {
1097 flushDiagnostics();
1098 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001099
1100 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001101 if (!uses)
1102 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +00001103
1104 UsesMap::mapped_type &V = (*uses)[vd];
1105 UsesVec *&vec = V.first;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001106 if (!vec)
1107 vec = new UsesVec();
1108
Ted Kremenek9e761722011-10-13 18:50:06 +00001109 return V;
1110 }
1111
Richard Smith2815e1a2012-05-25 02:17:09 +00001112 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
1113 getUses(vd).first->push_back(use);
Ted Kremenek9e761722011-10-13 18:50:06 +00001114 }
1115
1116 void handleSelfInit(const VarDecl *vd) {
1117 getUses(vd).second = true;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001118 }
1119
1120 void flushDiagnostics() {
1121 if (!uses)
1122 return;
Ted Kremenek609e3172011-02-02 23:35:53 +00001123
Richard Smith81891882012-05-24 23:45:35 +00001124 // FIXME: This iteration order, and thus the resulting diagnostic order,
1125 // is nondeterministic.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001126 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1127 const VarDecl *vd = i->first;
Ted Kremenek9e761722011-10-13 18:50:06 +00001128 const UsesMap::mapped_type &V = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +00001129
Ted Kremenek9e761722011-10-13 18:50:06 +00001130 UsesVec *vec = V.first;
1131 bool hasSelfInit = V.second;
1132
1133 // Specially handle the case where we have uses of an uninitialized
1134 // variable, but the root cause is an idiomatic self-init. We want
1135 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001136 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith2815e1a2012-05-25 02:17:09 +00001137 DiagnoseUninitializedUse(S, vd,
1138 UninitUse(vd->getInit()->IgnoreParenCasts(),
1139 /* isAlwaysUninit */ true),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001140 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +00001141 else {
1142 // Sort the uses by their SourceLocations. While not strictly
1143 // guaranteed to produce them in line/column order, this will provide
1144 // a stable ordering.
1145 std::sort(vec->begin(), vec->end(), SLocSort());
1146
1147 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1148 ++vi) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001149 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1150 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1151
1152 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek9e761722011-10-13 18:50:06 +00001153 // Skip further diagnostics for this variable. We try to warn only
1154 // on the first point at which a variable is used uninitialized.
1155 break;
1156 }
Chandler Carruth64fb9592011-04-05 18:18:08 +00001157 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001158
1159 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001160 delete vec;
1161 }
1162 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +00001163 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001164
1165private:
1166 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1167 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001168 if (i->getKind() == UninitUse::Always) {
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001169 return true;
1170 }
1171 }
1172 return false;
1173}
Ted Kremenek610068c2011-01-15 02:58:47 +00001174};
1175}
1176
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001177
1178//===----------------------------------------------------------------------===//
1179// -Wthread-safety
1180//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001181namespace clang {
1182namespace thread_safety {
Richard Smith2e515622012-02-03 04:45:26 +00001183typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1184typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramerecafd302012-03-26 14:05:40 +00001185typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001186
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001187struct SortDiagBySourceLocation {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001188 SourceManager &SM;
1189 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001190
1191 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1192 // Although this call will be slow, this is only called when outputting
1193 // multiple warnings.
Benjamin Kramerecafd302012-03-26 14:05:40 +00001194 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001195 }
1196};
1197
David Blaikie99ba9e32011-12-20 02:48:34 +00001198namespace {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001199class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1200 Sema &S;
1201 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +00001202 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001203
1204 // Helper functions
1205 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001206 // Gracefully handle rare cases when the analysis can't get a more
1207 // precise source location.
1208 if (!Loc.isValid())
1209 Loc = FunLocation;
Richard Smith2e515622012-02-03 04:45:26 +00001210 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1211 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001212 }
1213
1214 public:
Richard Smith2e515622012-02-03 04:45:26 +00001215 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1216 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001217
1218 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1219 /// We need to output diagnostics produced while iterating through
1220 /// the lockset in deterministic order, so this function orders diagnostics
1221 /// and outputs them.
1222 void emitDiagnostics() {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001223 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001224 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith2e515622012-02-03 04:45:26 +00001225 I != E; ++I) {
1226 S.Diag(I->first.first, I->first.second);
1227 const OptionalNotes &Notes = I->second;
1228 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1229 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1230 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001231 }
1232
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001233 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001234 PartialDiagnosticAt Warning(Loc,
1235 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1236 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001237 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001238 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1239 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1240 }
1241
1242 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1243 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1244 }
1245
Richard Smith2e515622012-02-03 04:45:26 +00001246 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1247 SourceLocation LocEndOfScope,
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001248 LockErrorKind LEK){
1249 unsigned DiagID = 0;
1250 switch (LEK) {
1251 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +00001252 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001253 break;
1254 case LEK_LockedSomeLoopIterations:
1255 DiagID = diag::warn_expecting_lock_held_on_loop;
1256 break;
1257 case LEK_LockedAtEndOfFunction:
1258 DiagID = diag::warn_no_unlock;
1259 break;
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001260 case LEK_NotLockedAtEndOfFunction:
1261 DiagID = diag::warn_expecting_locked;
1262 break;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001263 }
Richard Smith2e515622012-02-03 04:45:26 +00001264 if (LocEndOfScope.isInvalid())
1265 LocEndOfScope = FunEndLocation;
1266
1267 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
1268 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1269 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001270 }
1271
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001272
1273 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1274 SourceLocation Loc2) {
Richard Smith2e515622012-02-03 04:45:26 +00001275 PartialDiagnosticAt Warning(
1276 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1277 PartialDiagnosticAt Note(
1278 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1279 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001280 }
1281
1282 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1283 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +00001284 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1285 && "Only works for variables");
1286 unsigned DiagID = POK == POK_VarAccess?
1287 diag::warn_variable_requires_any_lock:
1288 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +00001289 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001290 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith2e515622012-02-03 04:45:26 +00001291 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001292 }
1293
1294 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001295 Name LockName, LockKind LK, SourceLocation Loc,
1296 Name *PossibleMatch) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +00001297 unsigned DiagID = 0;
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001298 if (PossibleMatch) {
1299 switch (POK) {
1300 case POK_VarAccess:
1301 DiagID = diag::warn_variable_requires_lock_precise;
1302 break;
1303 case POK_VarDereference:
1304 DiagID = diag::warn_var_deref_requires_lock_precise;
1305 break;
1306 case POK_FunctionCall:
1307 DiagID = diag::warn_fun_requires_lock_precise;
1308 break;
1309 }
1310 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001311 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001312 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1313 << *PossibleMatch);
1314 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1315 } else {
1316 switch (POK) {
1317 case POK_VarAccess:
1318 DiagID = diag::warn_variable_requires_lock;
1319 break;
1320 case POK_VarDereference:
1321 DiagID = diag::warn_var_deref_requires_lock;
1322 break;
1323 case POK_FunctionCall:
1324 DiagID = diag::warn_fun_requires_lock;
1325 break;
1326 }
1327 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001328 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001329 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001330 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001331 }
1332
1333 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001334 PartialDiagnosticAt Warning(Loc,
1335 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1336 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001337 }
1338};
1339}
1340}
David Blaikie99ba9e32011-12-20 02:48:34 +00001341}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001342
Ted Kremenek610068c2011-01-15 02:58:47 +00001343//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001344// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1345// warnings on a function, method, or block.
1346//===----------------------------------------------------------------------===//
1347
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001348clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1349 enableCheckFallThrough = 1;
1350 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001351 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001352}
1353
Chandler Carruth5d989942011-07-06 16:21:37 +00001354clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1355 : S(s),
1356 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001357 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001358 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001359 MaxCFGBlocksPerFunction(0),
1360 NumUninitAnalysisFunctions(0),
1361 NumUninitAnalysisVariables(0),
1362 MaxUninitAnalysisVariablesPerFunction(0),
1363 NumUninitAnalysisBlockVisits(0),
1364 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +00001365 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001366 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001367 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001368 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001369 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1370 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001371 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001372
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001373}
1374
Ted Kremenek351ba912011-02-23 01:52:04 +00001375static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001376 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001377 i = fscope->PossiblyUnreachableDiags.begin(),
1378 e = fscope->PossiblyUnreachableDiags.end();
1379 i != e; ++i) {
1380 const sema::PossiblyUnreachableDiag &D = *i;
1381 S.Diag(D.Loc, D.PD);
1382 }
1383}
1384
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001385void clang::sema::
1386AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001387 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001388 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001389
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001390 // We avoid doing analysis-based warnings when there are errors for
1391 // two reasons:
1392 // (1) The CFGs often can't be constructed (if the body is invalid), so
1393 // don't bother trying.
1394 // (2) The code already has problems; running the analysis just takes more
1395 // time.
David Blaikied6471f72011-09-25 23:23:43 +00001396 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +00001397
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001398 // Do not do any analysis for declarations in system headers if we are
1399 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001400 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001401 S.SourceMgr.isInSystemHeader(D->getLocation()))
1402 return;
1403
John McCalle0054f62010-08-25 05:56:39 +00001404 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +00001405 if (cast<DeclContext>(D)->isDependentContext())
1406 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001407
Ted Kremenek351ba912011-02-23 01:52:04 +00001408 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1409 // Flush out any possibly unreachable diagnostics.
1410 flushDiagnostics(S, fscope);
1411 return;
1412 }
1413
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001414 const Stmt *Body = D->getBody();
1415 assert(Body);
1416
Jordy Rosed2001872012-04-28 01:58:08 +00001417 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001418
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001419 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1420 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001421 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1422 AC.getCFGBuildOptions().AddEHEdges = false;
1423 AC.getCFGBuildOptions().AddInitializers = true;
1424 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rosefaadf482012-09-05 23:11:06 +00001425 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1426
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001427 // Force that certain expressions appear as CFGElements in the CFG. This
1428 // is used to speed up various analyses.
1429 // FIXME: This isn't the right factoring. This is here for initial
1430 // prototyping, but we need a way for analyses to say what expressions they
1431 // expect to always be CFGElements and then fill in the BuildOptions
1432 // appropriately. This is essentially a layering violation.
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001433 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
1434 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001435 AC.getCFGBuildOptions().setAllAlwaysAdd();
1436 }
1437 else {
1438 AC.getCFGBuildOptions()
1439 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smith6cfa78f2012-07-17 01:27:33 +00001440 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001441 .setAlwaysAdd(Stmt::BlockExprClass)
1442 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1443 .setAlwaysAdd(Stmt::DeclRefExprClass)
1444 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001445 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1446 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001447 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001448
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001449 // Construct the analysis context with the specified CFG build options.
1450
Ted Kremenek351ba912011-02-23 01:52:04 +00001451 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +00001452 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001453 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001454
1455 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001456 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001457 i = fscope->PossiblyUnreachableDiags.begin(),
1458 e = fscope->PossiblyUnreachableDiags.end();
1459 i != e; ++i) {
1460 if (const Stmt *stmt = i->stmt)
1461 AC.registerForcedBlockExpression(stmt);
1462 }
1463
1464 if (AC.getCFG()) {
1465 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001466 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001467 i = fscope->PossiblyUnreachableDiags.begin(),
1468 e = fscope->PossiblyUnreachableDiags.end();
1469 i != e; ++i)
1470 {
1471 const sema::PossiblyUnreachableDiag &D = *i;
1472 bool processed = false;
1473 if (const Stmt *stmt = i->stmt) {
1474 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +00001475 CFGReverseBlockReachabilityAnalysis *cra =
1476 AC.getCFGReachablityAnalysis();
1477 // FIXME: We should be able to assert that block is non-null, but
1478 // the CFG analysis can skip potentially-evaluated expressions in
1479 // edge cases; see test/Sema/vla-2.c.
1480 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001481 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001482 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001483 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001484 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001485 }
1486 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001487 if (!processed) {
1488 // Emit the warning anyway if we cannot map to a basic block.
1489 S.Diag(D.Loc, D.PD);
1490 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001491 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001492 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001493
1494 if (!analyzed)
1495 flushDiagnostics(S, fscope);
1496 }
1497
1498
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001499 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +00001500 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001501 const CheckFallThroughDiagnostics &CD =
1502 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +00001503 : (isa<CXXMethodDecl>(D) &&
1504 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1505 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1506 ? CheckFallThroughDiagnostics::MakeForLambda()
1507 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001508 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001509 }
1510
1511 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +00001512 if (P.enableCheckUnreachable) {
1513 // Only check for unreachable code on non-template instantiations.
1514 // Different template instantiations can effectively change the control-flow
1515 // and it is very difficult to prove that a snippet of code in a template
1516 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +00001517 bool isTemplateInstantiation = false;
1518 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1519 isTemplateInstantiation = Function->isTemplateInstantiation();
1520 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +00001521 CheckUnreachable(S, AC);
1522 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001523
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001524 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +00001525 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001526 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +00001527 SourceLocation FEL = AC.getDecl()->getLocEnd();
1528 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001529 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1530 Reporter.emitDiagnostics();
1531 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001532
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001533 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001534 != DiagnosticsEngine::Ignored ||
Richard Smith2815e1a2012-05-25 02:17:09 +00001535 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1536 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +00001537 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001538 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001539 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001540 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001541 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001542 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001543 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001544 reporter, stats);
1545
1546 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1547 ++NumUninitAnalysisFunctions;
1548 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1549 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1550 MaxUninitAnalysisVariablesPerFunction =
1551 std::max(MaxUninitAnalysisVariablesPerFunction,
1552 stats.NumVariablesAnalyzed);
1553 MaxUninitAnalysisBlockVisitsPerFunction =
1554 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1555 stats.NumBlockVisits);
1556 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001557 }
1558 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001559
Alexander Kornienko19736342012-06-02 01:01:07 +00001560 bool FallThroughDiagFull =
1561 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1562 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001563 bool FallThroughDiagPerFunction =
1564 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko19736342012-06-02 01:01:07 +00001565 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001566 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko19736342012-06-02 01:01:07 +00001567 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001568 }
1569
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001570 if (S.getLangOpts().ObjCARCWeak &&
1571 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1572 D->getLocStart()) != DiagnosticsEngine::Ignored)
1573 diagnoseRepeatedUseOfWeak(S, fscope, D);
1574
Chandler Carruth5d989942011-07-06 16:21:37 +00001575 // Collect statistics about the CFG if it was built.
1576 if (S.CollectStats && AC.isCFGBuilt()) {
1577 ++NumFunctionsAnalyzed;
1578 if (CFG *cfg = AC.getCFG()) {
1579 // If we successfully built a CFG for this context, record some more
1580 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001581 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001582 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001583 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001584 } else {
1585 ++NumFunctionsWithBadCFGs;
1586 }
1587 }
1588}
1589
1590void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1591 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1592
1593 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1594 unsigned AvgCFGBlocksPerFunction =
1595 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1596 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1597 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1598 << " " << NumCFGBlocks << " CFG blocks built.\n"
1599 << " " << AvgCFGBlocksPerFunction
1600 << " average CFG blocks per function.\n"
1601 << " " << MaxCFGBlocksPerFunction
1602 << " max CFG blocks per function.\n";
1603
1604 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1605 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1606 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1607 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1608 llvm::errs() << NumUninitAnalysisFunctions
1609 << " functions analyzed for uninitialiazed variables\n"
1610 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1611 << " " << AvgUninitVariablesPerFunction
1612 << " average variables per function.\n"
1613 << " " << MaxUninitAnalysisVariablesPerFunction
1614 << " max variables per function.\n"
1615 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1616 << " " << AvgUninitBlockVisitsPerFunction
1617 << " average block visits per function.\n"
1618 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1619 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001620}