blob: a20817f965008eb66d5c3b396c4070e2e7bc98c9 [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"
Jordan Roseb5cd1222012-10-11 16:10:19 +000030#include "clang/AST/ParentMap.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000031#include "clang/AST/StmtVisitor.h"
Richard Smithe0d3b4c2012-05-03 18:27:39 +000032#include "clang/AST/RecursiveASTVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000033#include "clang/Analysis/AnalysisContext.h"
34#include "clang/Analysis/CFG.h"
35#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000036#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000037#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000038#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000039#include "clang/Analysis/Analyses/UninitializedValues.h"
Alexander Kornienko66da0ab2012-09-28 22:24:03 +000040#include "llvm/ADT/ArrayRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000041#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000042#include "llvm/ADT/FoldingSet.h"
43#include "llvm/ADT/ImmutableMap.h"
44#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko19523542012-09-29 11:40:46 +000045#include "llvm/ADT/SmallString.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000046#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000047#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000048#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000049#include <algorithm>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000050#include <iterator>
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000051#include <vector>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000052#include <deque>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000053
54using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Unreachable code analysis.
58//===----------------------------------------------------------------------===//
59
60namespace {
61 class UnreachableCodeHandler : public reachable_code::Callback {
62 Sema &S;
63 public:
64 UnreachableCodeHandler(Sema &s) : S(s) {}
65
66 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
67 S.Diag(L, diag::warn_unreachable) << R1 << R2;
68 }
69 };
70}
71
72/// CheckUnreachable - Check for unreachable code.
Ted Kremenek1d26f482011-10-24 01:32:45 +000073static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000074 UnreachableCodeHandler UC(S);
75 reachable_code::FindUnreachableCode(AC, UC);
76}
77
78//===----------------------------------------------------------------------===//
79// Check for missing return value.
80//===----------------------------------------------------------------------===//
81
John McCall16565aa2010-05-16 09:34:11 +000082enum ControlFlowKind {
83 UnknownFallThrough,
84 NeverFallThrough,
85 MaybeFallThrough,
86 AlwaysFallThrough,
87 NeverFallThroughOrReturn
88};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000089
90/// CheckFallThrough - Check that we don't fall off the end of a
91/// Statement that should return a value.
92///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000093/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
94/// MaybeFallThrough iff we might or might not fall off the end,
95/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
96/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000097/// statement but we may return. We assume that functions not marked noreturn
98/// will return.
Ted Kremenek1d26f482011-10-24 01:32:45 +000099static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000100 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +0000101 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000102
103 // The CFG leaves in dead things, and we don't want the dead code paths to
104 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000105 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000106 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000107 live);
108
109 bool AddEHEdges = AC.getAddEHEdges();
110 if (!AddEHEdges && count != cfg->getNumBlockIDs())
111 // When there are things remaining dead, and we didn't add EH edges
112 // from CallExprs to the catch clauses, we have to go back and
113 // mark them as live.
114 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
115 CFGBlock &b = **I;
116 if (!live[b.getBlockID()]) {
117 if (b.pred_begin() == b.pred_end()) {
118 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
119 // When not adding EH edges from calls, catch clauses
120 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000121 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000122 continue;
123 }
124 }
125 }
126
127 // Now we know what is live, we check the live precessors of the exit block
128 // and look for fall through paths, being careful to ignore normal returns,
129 // and exceptional paths.
130 bool HasLiveReturn = false;
131 bool HasFakeEdge = false;
132 bool HasPlainEdge = false;
133 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000134
135 // Ignore default cases that aren't likely to be reachable because all
136 // enums in a switch(X) have explicit case statements.
137 CFGBlock::FilterOptions FO;
138 FO.IgnoreDefaultsWithCoveredEnums = 1;
139
140 for (CFGBlock::filtered_pred_iterator
141 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
142 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000143 if (!live[B.getBlockID()])
144 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000145
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000146 // Skip blocks which contain an element marked as no-return. They don't
147 // represent actually viable edges into the exit block, so mark them as
148 // abnormal.
149 if (B.hasNoReturnElement()) {
150 HasAbnormalEdge = true;
151 continue;
152 }
153
Ted Kremenek5811f592011-01-26 04:49:52 +0000154 // Destructors can appear after the 'return' in the CFG. This is
155 // normal. We need to look pass the destructors for the return
156 // statement (if it exists).
157 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000158
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000159 for ( ; ri != re ; ++ri)
160 if (isa<CFGStmt>(*ri))
Ted Kremenek5811f592011-01-26 04:49:52 +0000161 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000162
Ted Kremenek5811f592011-01-26 04:49:52 +0000163 // No more CFGElements in the block?
164 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000165 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
166 HasAbnormalEdge = true;
167 continue;
168 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000169 // A labeled empty statement, or the entry block...
170 HasPlainEdge = true;
171 continue;
172 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000173
Ted Kremenek5811f592011-01-26 04:49:52 +0000174 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000175 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000176 if (isa<ReturnStmt>(S)) {
177 HasLiveReturn = true;
178 continue;
179 }
180 if (isa<ObjCAtThrowStmt>(S)) {
181 HasFakeEdge = true;
182 continue;
183 }
184 if (isa<CXXThrowExpr>(S)) {
185 HasFakeEdge = true;
186 continue;
187 }
Chad Rosier8cd64b42012-06-11 20:47:18 +0000188 if (isa<MSAsmStmt>(S)) {
189 // TODO: Verify this is correct.
190 HasFakeEdge = true;
191 HasLiveReturn = true;
192 continue;
193 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000194 if (isa<CXXTryStmt>(S)) {
195 HasAbnormalEdge = true;
196 continue;
197 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000198 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
199 == B.succ_end()) {
200 HasAbnormalEdge = true;
201 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000202 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000203
204 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000205 }
206 if (!HasPlainEdge) {
207 if (HasLiveReturn)
208 return NeverFallThrough;
209 return NeverFallThroughOrReturn;
210 }
211 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
212 return MaybeFallThrough;
213 // This says AlwaysFallThrough for calls to functions that are not marked
214 // noreturn, that don't return. If people would like this warning to be more
215 // accurate, such functions should be marked as noreturn.
216 return AlwaysFallThrough;
217}
218
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000219namespace {
220
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000221struct CheckFallThroughDiagnostics {
222 unsigned diag_MaybeFallThrough_HasNoReturn;
223 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
224 unsigned diag_AlwaysFallThrough_HasNoReturn;
225 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
226 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000227 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000228 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000229
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000230 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000231 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000232 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000233 D.diag_MaybeFallThrough_HasNoReturn =
234 diag::warn_falloff_noreturn_function;
235 D.diag_MaybeFallThrough_ReturnsNonVoid =
236 diag::warn_maybe_falloff_nonvoid_function;
237 D.diag_AlwaysFallThrough_HasNoReturn =
238 diag::warn_falloff_noreturn_function;
239 D.diag_AlwaysFallThrough_ReturnsNonVoid =
240 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000241
242 // Don't suggest that virtual functions be marked "noreturn", since they
243 // might be overridden by non-noreturn functions.
244 bool isVirtualMethod = false;
245 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
246 isVirtualMethod = Method->isVirtual();
247
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000248 // Don't suggest that template instantiations be marked "noreturn"
249 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000250 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
251 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000252
253 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000254 D.diag_NeverFallThroughOrReturn =
255 diag::warn_suggest_noreturn_function;
256 else
257 D.diag_NeverFallThroughOrReturn = 0;
258
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000259 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000260 return D;
261 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000262
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000263 static CheckFallThroughDiagnostics MakeForBlock() {
264 CheckFallThroughDiagnostics D;
265 D.diag_MaybeFallThrough_HasNoReturn =
266 diag::err_noreturn_block_has_return_expr;
267 D.diag_MaybeFallThrough_ReturnsNonVoid =
268 diag::err_maybe_falloff_nonvoid_block;
269 D.diag_AlwaysFallThrough_HasNoReturn =
270 diag::err_noreturn_block_has_return_expr;
271 D.diag_AlwaysFallThrough_ReturnsNonVoid =
272 diag::err_falloff_nonvoid_block;
273 D.diag_NeverFallThroughOrReturn =
274 diag::warn_suggest_noreturn_block;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000275 D.funMode = Block;
276 return D;
277 }
278
279 static CheckFallThroughDiagnostics MakeForLambda() {
280 CheckFallThroughDiagnostics D;
281 D.diag_MaybeFallThrough_HasNoReturn =
282 diag::err_noreturn_lambda_has_return_expr;
283 D.diag_MaybeFallThrough_ReturnsNonVoid =
284 diag::warn_maybe_falloff_nonvoid_lambda;
285 D.diag_AlwaysFallThrough_HasNoReturn =
286 diag::err_noreturn_lambda_has_return_expr;
287 D.diag_AlwaysFallThrough_ReturnsNonVoid =
288 diag::warn_falloff_nonvoid_lambda;
289 D.diag_NeverFallThroughOrReturn = 0;
290 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000291 return D;
292 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000293
David Blaikied6471f72011-09-25 23:23:43 +0000294 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000295 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000296 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000297 return (ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000299 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000300 && (!HasNoReturn ||
301 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000302 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000303 && (!ReturnsVoid ||
304 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000305 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000306 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000307
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000308 // For blocks / lambdas.
309 return ReturnsVoid && !HasNoReturn
310 && ((funMode == Lambda) ||
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000311 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000312 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000313 }
314};
315
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000316}
317
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000318/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
319/// function that should return a value. Check that we don't fall off the end
320/// of a noreturn function. We assume that functions and blocks not marked
321/// noreturn will return.
322static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000323 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000324 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000325 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000326
327 bool ReturnsVoid = false;
328 bool HasNoReturn = false;
329
330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
331 ReturnsVoid = FD->getResultType()->isVoidType();
332 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000333 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000334 }
335 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
336 ReturnsVoid = MD->getResultType()->isVoidType();
337 HasNoReturn = MD->hasAttr<NoReturnAttr>();
338 }
339 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000340 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000341 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000342 BlockTy->getPointeeType()->getAs<FunctionType>()) {
343 if (FT->getResultType()->isVoidType())
344 ReturnsVoid = true;
345 if (FT->getNoReturnAttr())
346 HasNoReturn = true;
347 }
348 }
349
David Blaikied6471f72011-09-25 23:23:43 +0000350 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000351
352 // Short circuit for compilation speed.
353 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
354 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000355
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000356 // FIXME: Function try block
357 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
358 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000359 case UnknownFallThrough:
360 break;
361
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000362 case MaybeFallThrough:
363 if (HasNoReturn)
364 S.Diag(Compound->getRBracLoc(),
365 CD.diag_MaybeFallThrough_HasNoReturn);
366 else if (!ReturnsVoid)
367 S.Diag(Compound->getRBracLoc(),
368 CD.diag_MaybeFallThrough_ReturnsNonVoid);
369 break;
370 case AlwaysFallThrough:
371 if (HasNoReturn)
372 S.Diag(Compound->getRBracLoc(),
373 CD.diag_AlwaysFallThrough_HasNoReturn);
374 else if (!ReturnsVoid)
375 S.Diag(Compound->getRBracLoc(),
376 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
377 break;
378 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000379 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
380 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
381 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000382 << 0 << FD;
383 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
384 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
385 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000386 } else {
387 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
388 }
389 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000390 break;
391 case NeverFallThrough:
392 break;
393 }
394 }
395}
396
397//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000398// -Wuninitialized
399//===----------------------------------------------------------------------===//
400
Ted Kremenek6f417152011-04-04 20:56:00 +0000401namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000402/// ContainsReference - A visitor class to search for references to
403/// a particular declaration (the needle) within any evaluated component of an
404/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000405class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000406 bool FoundReference;
407 const DeclRefExpr *Needle;
408
Ted Kremenek6f417152011-04-04 20:56:00 +0000409public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000410 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
411 : EvaluatedExprVisitor<ContainsReference>(Context),
412 FoundReference(false), Needle(Needle) {}
413
414 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000415 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000416 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000417 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000418
419 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000420 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000421
422 void VisitDeclRefExpr(DeclRefExpr *E) {
423 if (E == Needle)
424 FoundReference = true;
425 else
426 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000427 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000428
429 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000430};
431}
432
David Blaikie4f4f3492011-09-10 05:35:08 +0000433static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000434 QualType VariableTy = VD->getType().getCanonicalType();
435 if (VariableTy->isBlockPointerType() &&
436 !VD->hasAttr<BlocksAttr>()) {
437 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
438 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
439 return true;
440 }
441
David Blaikie4f4f3492011-09-10 05:35:08 +0000442 // Don't issue a fixit if there is already an initializer.
443 if (VD->getInit())
444 return false;
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000445
David Blaikie4f4f3492011-09-10 05:35:08 +0000446 // Suggest possible initialization (if any).
David Blaikie2c0abf42012-04-30 18:27:22 +0000447 std::string Init = S.getFixItZeroInitializerForType(VariableTy);
448 if (Init.empty())
David Blaikie4f4f3492011-09-10 05:35:08 +0000449 return false;
Richard Trieu7b0a3e32012-05-03 01:09:59 +0000450
451 // Don't suggest a fixit inside macros.
452 if (VD->getLocEnd().isMacroID())
453 return false;
454
Richard Smith7984de32012-01-12 23:53:29 +0000455 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000456
Richard Smith7984de32012-01-12 23:53:29 +0000457 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
458 << FixItHint::CreateInsertion(Loc, Init);
459 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000460}
461
Richard Smithbdb97ff2012-05-26 06:20:46 +0000462/// Create a fixit to remove an if-like statement, on the assumption that its
463/// condition is CondVal.
464static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
465 const Stmt *Else, bool CondVal,
466 FixItHint &Fixit1, FixItHint &Fixit2) {
467 if (CondVal) {
468 // If condition is always true, remove all but the 'then'.
469 Fixit1 = FixItHint::CreateRemoval(
470 CharSourceRange::getCharRange(If->getLocStart(),
471 Then->getLocStart()));
472 if (Else) {
473 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
474 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
475 Fixit2 = FixItHint::CreateRemoval(
476 SourceRange(ElseKwLoc, Else->getLocEnd()));
477 }
478 } else {
479 // If condition is always false, remove all but the 'else'.
480 if (Else)
481 Fixit1 = FixItHint::CreateRemoval(
482 CharSourceRange::getCharRange(If->getLocStart(),
483 Else->getLocStart()));
484 else
485 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
486 }
487}
488
489/// DiagUninitUse -- Helper function to produce a diagnostic for an
490/// uninitialized use of a variable.
491static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
492 bool IsCapturedByBlock) {
493 bool Diagnosed = false;
494
495 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith2815e1a2012-05-25 02:17:09 +0000496 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
497 I != E; ++I) {
Richard Smithbdb97ff2012-05-26 06:20:46 +0000498 assert(Use.getKind() == UninitUse::Sometimes);
499
500 const Expr *User = Use.getUser();
Richard Smith2815e1a2012-05-25 02:17:09 +0000501 const Stmt *Term = I->Terminator;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000502
503 // Information used when building the diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000504 unsigned DiagKind;
David Blaikie0bea8632012-10-08 01:11:04 +0000505 StringRef Str;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000506 SourceRange Range;
507
508 // FixIts to suppress the diagnosic by removing the dead condition.
509 // For all binary terminators, branch 0 is taken if the condition is true,
510 // and branch 1 is taken if the condition is false.
511 int RemoveDiagKind = -1;
512 const char *FixitStr =
513 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
514 : (I->Output ? "1" : "0");
515 FixItHint Fixit1, Fixit2;
516
Richard Smith2815e1a2012-05-25 02:17:09 +0000517 switch (Term->getStmtClass()) {
518 default:
Richard Smithbdb97ff2012-05-26 06:20:46 +0000519 // Don't know how to report this. Just fall back to 'may be used
520 // uninitialized'. This happens for range-based for, which the user
521 // can't explicitly fix.
522 // FIXME: This also happens if the first use of a variable is always
523 // uninitialized, eg "for (int n; n < 10; ++n)". We should report that
524 // with the 'is uninitialized' diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000525 continue;
526
527 // "condition is true / condition is false".
Richard Smithbdb97ff2012-05-26 06:20:46 +0000528 case Stmt::IfStmtClass: {
529 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000530 DiagKind = 0;
531 Str = "if";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000532 Range = IS->getCond()->getSourceRange();
533 RemoveDiagKind = 0;
534 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
535 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000536 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000537 }
538 case Stmt::ConditionalOperatorClass: {
539 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000540 DiagKind = 0;
541 Str = "?:";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000542 Range = CO->getCond()->getSourceRange();
543 RemoveDiagKind = 0;
544 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
545 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000546 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000547 }
Richard Smith2815e1a2012-05-25 02:17:09 +0000548 case Stmt::BinaryOperatorClass: {
549 const BinaryOperator *BO = cast<BinaryOperator>(Term);
550 if (!BO->isLogicalOp())
551 continue;
552 DiagKind = 0;
553 Str = BO->getOpcodeStr();
554 Range = BO->getLHS()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000555 RemoveDiagKind = 0;
556 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
557 (BO->getOpcode() == BO_LOr && !I->Output))
558 // true && y -> y, false || y -> y.
559 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
560 BO->getOperatorLoc()));
561 else
562 // false && y -> false, true || y -> true.
563 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000564 break;
565 }
566
567 // "loop is entered / loop is exited".
568 case Stmt::WhileStmtClass:
569 DiagKind = 1;
570 Str = "while";
571 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000572 RemoveDiagKind = 1;
573 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000574 break;
575 case Stmt::ForStmtClass:
576 DiagKind = 1;
577 Str = "for";
578 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000579 RemoveDiagKind = 1;
580 if (I->Output)
581 Fixit1 = FixItHint::CreateRemoval(Range);
582 else
583 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000584 break;
585
586 // "condition is true / loop is exited".
587 case Stmt::DoStmtClass:
588 DiagKind = 2;
589 Str = "do";
590 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000591 RemoveDiagKind = 1;
592 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000593 break;
594
595 // "switch case is taken".
596 case Stmt::CaseStmtClass:
597 DiagKind = 3;
598 Str = "case";
599 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
600 break;
601 case Stmt::DefaultStmtClass:
602 DiagKind = 3;
603 Str = "default";
604 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
605 break;
606 }
607
Richard Smithbdb97ff2012-05-26 06:20:46 +0000608 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
609 << VD->getDeclName() << IsCapturedByBlock << DiagKind
610 << Str << I->Output << Range;
611 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
612 << IsCapturedByBlock << User->getSourceRange();
613 if (RemoveDiagKind != -1)
614 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
615 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
616
617 Diagnosed = true;
Richard Smith2815e1a2012-05-25 02:17:09 +0000618 }
Richard Smithbdb97ff2012-05-26 06:20:46 +0000619
620 if (!Diagnosed)
621 S.Diag(Use.getUser()->getLocStart(),
622 Use.getKind() == UninitUse::Always ? diag::warn_uninit_var
623 : diag::warn_maybe_uninit_var)
624 << VD->getDeclName() << IsCapturedByBlock
625 << Use.getUser()->getSourceRange();
Richard Smith2815e1a2012-05-25 02:17:09 +0000626}
627
Chandler Carruth262d50e2011-04-05 18:27:05 +0000628/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
629/// uninitialized variable. This manages the different forms of diagnostic
630/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith2815e1a2012-05-25 02:17:09 +0000631/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruth262d50e2011-04-05 18:27:05 +0000632/// false.
633static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith2815e1a2012-05-25 02:17:09 +0000634 const UninitUse &Use,
Ted Kremenek9e761722011-10-13 18:50:06 +0000635 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000636
Richard Smith2815e1a2012-05-25 02:17:09 +0000637 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieuf6278e52012-05-09 21:08:22 +0000638 // Inspect the initializer of the variable declaration which is
639 // being referenced prior to its initialization. We emit
640 // specialized diagnostics for self-initialization, and we
641 // specifically avoid warning about self references which take the
642 // form of:
643 //
644 // int x = x;
645 //
646 // This is used to indicate to GCC that 'x' is intentionally left
647 // uninitialized. Proven code paths which access 'x' in
648 // an uninitialized state after this will still warn.
649 if (const Expr *Initializer = VD->getInit()) {
650 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
651 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000652
Richard Trieuf6278e52012-05-09 21:08:22 +0000653 ContainsReference CR(S.Context, DRE);
654 CR.Visit(const_cast<Expr*>(Initializer));
655 if (CR.doesContainReference()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000656 S.Diag(DRE->getLocStart(),
657 diag::warn_uninit_self_reference_in_init)
Richard Trieuf6278e52012-05-09 21:08:22 +0000658 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
659 return true;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000660 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000661 }
Richard Trieuf6278e52012-05-09 21:08:22 +0000662
Richard Smithbdb97ff2012-05-26 06:20:46 +0000663 DiagUninitUse(S, VD, Use, false);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000664 } else {
Richard Smith2815e1a2012-05-25 02:17:09 +0000665 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smithbdb97ff2012-05-26 06:20:46 +0000666 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
667 S.Diag(BE->getLocStart(),
668 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000669 << VD->getDeclName();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000670 else
671 DiagUninitUse(S, VD, Use, true);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000672 }
673
674 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000675 // the initializer of that declaration & we didn't already suggest
676 // an initialization fixit.
Richard Trieuf6278e52012-05-09 21:08:22 +0000677 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000678 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
679 << VD->getDeclName();
680
Chandler Carruth262d50e2011-04-05 18:27:05 +0000681 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000682}
683
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000684namespace {
685 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
686 public:
687 FallthroughMapper(Sema &S)
688 : FoundSwitchStatements(false),
689 S(S) {
690 }
691
692 bool foundSwitchStatements() const { return FoundSwitchStatements; }
693
694 void markFallthroughVisited(const AttributedStmt *Stmt) {
695 bool Found = FallthroughStmts.erase(Stmt);
696 assert(Found);
Kaelyn Uhrain3bb29942012-05-03 19:46:38 +0000697 (void)Found;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000698 }
699
700 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
701
702 const AttrStmts &getFallthroughStmts() const {
703 return FallthroughStmts;
704 }
705
706 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
707 int UnannotatedCnt = 0;
708 AnnotatedCnt = 0;
709
710 std::deque<const CFGBlock*> BlockQueue;
711
712 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
713
714 while (!BlockQueue.empty()) {
715 const CFGBlock *P = BlockQueue.front();
716 BlockQueue.pop_front();
717
718 const Stmt *Term = P->getTerminator();
719 if (Term && isa<SwitchStmt>(Term))
720 continue; // Switch statement, good.
721
722 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
723 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
724 continue; // Previous case label has no statements, good.
725
726 if (P->pred_begin() == P->pred_end()) { // The block is unreachable.
727 // This only catches trivially unreachable blocks.
728 for (CFGBlock::const_iterator ElIt = P->begin(), ElEnd = P->end();
729 ElIt != ElEnd; ++ElIt) {
730 if (const CFGStmt *CS = ElIt->getAs<CFGStmt>()){
731 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
732 S.Diag(AS->getLocStart(),
733 diag::warn_fallthrough_attr_unreachable);
734 markFallthroughVisited(AS);
735 ++AnnotatedCnt;
736 }
737 // Don't care about other unreachable statements.
738 }
739 }
740 // If there are no unreachable statements, this may be a special
741 // case in CFG:
742 // case X: {
743 // A a; // A has a destructor.
744 // break;
745 // }
746 // // <<<< This place is represented by a 'hanging' CFG block.
747 // case Y:
748 continue;
749 }
750
751 const Stmt *LastStmt = getLastStmt(*P);
752 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
753 markFallthroughVisited(AS);
754 ++AnnotatedCnt;
755 continue; // Fallthrough annotation, good.
756 }
757
758 if (!LastStmt) { // This block contains no executable statements.
759 // Traverse its predecessors.
760 std::copy(P->pred_begin(), P->pred_end(),
761 std::back_inserter(BlockQueue));
762 continue;
763 }
764
765 ++UnannotatedCnt;
766 }
767 return !!UnannotatedCnt;
768 }
769
770 // RecursiveASTVisitor setup.
771 bool shouldWalkTypesOfTypeLocs() const { return false; }
772
773 bool VisitAttributedStmt(AttributedStmt *S) {
774 if (asFallThroughAttr(S))
775 FallthroughStmts.insert(S);
776 return true;
777 }
778
779 bool VisitSwitchStmt(SwitchStmt *S) {
780 FoundSwitchStatements = true;
781 return true;
782 }
783
784 private:
785
786 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
787 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
788 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
789 return AS;
790 }
791 return 0;
792 }
793
794 static const Stmt *getLastStmt(const CFGBlock &B) {
795 if (const Stmt *Term = B.getTerminator())
796 return Term;
797 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
798 ElemEnd = B.rend();
799 ElemIt != ElemEnd; ++ElemIt) {
800 if (const CFGStmt *CS = ElemIt->getAs<CFGStmt>())
801 return CS->getStmt();
802 }
803 // Workaround to detect a statement thrown out by CFGBuilder:
804 // case X: {} case Y:
805 // case X: ; case Y:
806 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
807 if (!isa<SwitchCase>(SW->getSubStmt()))
808 return SW->getSubStmt();
809
810 return 0;
811 }
812
813 bool FoundSwitchStatements;
814 AttrStmts FallthroughStmts;
815 Sema &S;
816 };
817}
818
Alexander Kornienko19736342012-06-02 01:01:07 +0000819static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Sean Huntc2f51cf2012-06-15 21:22:05 +0000820 bool PerFunction) {
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000821 FallthroughMapper FM(S);
822 FM.TraverseStmt(AC.getBody());
823
824 if (!FM.foundSwitchStatements())
825 return;
826
Sean Huntc2f51cf2012-06-15 21:22:05 +0000827 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko19736342012-06-02 01:01:07 +0000828 return;
829
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000830 CFG *Cfg = AC.getCFG();
831
832 if (!Cfg)
833 return;
834
835 int AnnotatedCnt;
836
837 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
838 const CFGBlock &B = **I;
839 const Stmt *Label = B.getLabel();
840
841 if (!Label || !isa<SwitchCase>(Label))
842 continue;
843
844 if (!FM.checkFallThroughIntoBlock(B, AnnotatedCnt))
845 continue;
846
Alexander Kornienko19736342012-06-02 01:01:07 +0000847 S.Diag(Label->getLocStart(),
Sean Huntc2f51cf2012-06-15 21:22:05 +0000848 PerFunction ? diag::warn_unannotated_fallthrough_per_function
849 : diag::warn_unannotated_fallthrough);
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000850
851 if (!AnnotatedCnt) {
852 SourceLocation L = Label->getLocStart();
853 if (L.isMacroID())
854 continue;
855 if (S.getLangOpts().CPlusPlus0x) {
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000856 const Stmt *Term = B.getTerminator();
857 if (!(B.empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000858 Preprocessor &PP = S.getPreprocessor();
859 TokenValue Tokens[] = {
860 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
861 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
862 tok::r_square, tok::r_square
863 };
Dmitri Gribenko19523542012-09-29 11:40:46 +0000864 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
865 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
866 if (!MacroName.empty())
867 AnnotationSpelling = MacroName;
868 SmallString<64> TextToInsert(AnnotationSpelling);
869 TextToInsert += "; ";
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000870 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienko66da0ab2012-09-28 22:24:03 +0000871 AnnotationSpelling <<
Dmitri Gribenko19523542012-09-29 11:40:46 +0000872 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000873 }
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000874 }
875 S.Diag(L, diag::note_insert_break_fixit) <<
876 FixItHint::CreateInsertion(L, "break; ");
877 }
878 }
879
880 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
881 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
882 E = Fallthroughs.end();
883 I != E; ++I) {
884 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
885 }
886
887}
888
Ted Kremenek610068c2011-01-15 02:58:47 +0000889namespace {
Jordan Rose20441c52012-09-28 22:29:02 +0000890typedef std::pair<const Stmt *,
891 sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
892 StmtUsesPair;
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000893
Jordan Rose20441c52012-09-28 22:29:02 +0000894class StmtUseSorter {
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000895 const SourceManager &SM;
896
897public:
Jordan Rose20441c52012-09-28 22:29:02 +0000898 explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000899
900 bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
901 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
902 RHS.first->getLocStart());
903 }
904};
Jordan Rose20441c52012-09-28 22:29:02 +0000905}
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000906
Jordan Rosec0e44452012-10-29 17:46:47 +0000907static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
908 const Stmt *S) {
Jordan Roseb5cd1222012-10-11 16:10:19 +0000909 assert(S);
910
911 do {
912 switch (S->getStmtClass()) {
Jordan Roseb5cd1222012-10-11 16:10:19 +0000913 case Stmt::ForStmtClass:
914 case Stmt::WhileStmtClass:
915 case Stmt::CXXForRangeStmtClass:
916 case Stmt::ObjCForCollectionStmtClass:
917 return true;
Jordan Rosec0e44452012-10-29 17:46:47 +0000918 case Stmt::DoStmtClass: {
919 const Expr *Cond = cast<DoStmt>(S)->getCond();
920 llvm::APSInt Val;
921 if (!Cond->EvaluateAsInt(Val, Ctx))
922 return true;
923 return Val.getBoolValue();
924 }
Jordan Roseb5cd1222012-10-11 16:10:19 +0000925 default:
926 break;
927 }
928 } while ((S = PM.getParent(S)));
929
930 return false;
931}
932
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000933
934static void diagnoseRepeatedUseOfWeak(Sema &S,
935 const sema::FunctionScopeInfo *CurFn,
Jordan Roseb5cd1222012-10-11 16:10:19 +0000936 const Decl *D,
937 const ParentMap &PM) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000938 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
939 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
940 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
941
Jordan Rosec0e44452012-10-29 17:46:47 +0000942 ASTContext &Ctx = S.getASTContext();
943
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000944 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
945
946 // Extract all weak objects that are referenced more than once.
947 SmallVector<StmtUsesPair, 8> UsesByStmt;
948 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
949 I != E; ++I) {
950 const WeakUseVector &Uses = I->second;
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000951
952 // Find the first read of the weak object.
953 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
954 for ( ; UI != UE; ++UI) {
955 if (UI->isUnsafe())
956 break;
957 }
958
959 // If there were only writes to this object, don't warn.
960 if (UI == UE)
961 continue;
962
Jordan Roseb5cd1222012-10-11 16:10:19 +0000963 // If there was only one read, followed by any number of writes, and the
Jordan Rosec0e44452012-10-29 17:46:47 +0000964 // read is not within a loop, don't warn. Additionally, don't warn in a
965 // loop if the base object is a local variable -- local variables are often
966 // changed in loops.
Jordan Roseb5cd1222012-10-11 16:10:19 +0000967 if (UI == Uses.begin()) {
968 WeakUseVector::const_iterator UI2 = UI;
969 for (++UI2; UI2 != UE; ++UI2)
970 if (UI2->isUnsafe())
971 break;
972
Jordan Rosec0e44452012-10-29 17:46:47 +0000973 if (UI2 == UE) {
974 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Roseb5cd1222012-10-11 16:10:19 +0000975 continue;
Jordan Rosec0e44452012-10-29 17:46:47 +0000976
977 const WeakObjectProfileTy &Profile = I->first;
978 if (!Profile.isExactProfile())
979 continue;
980
981 const NamedDecl *Base = Profile.getBase();
982 if (!Base)
983 Base = Profile.getProperty();
984 assert(Base && "A profile always has a base or property.");
985
986 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
987 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
988 continue;
989 }
Jordan Roseb5cd1222012-10-11 16:10:19 +0000990 }
991
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000992 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
993 }
994
995 if (UsesByStmt.empty())
996 return;
997
998 // Sort by first use so that we emit the warnings in a deterministic order.
999 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Jordan Rose20441c52012-09-28 22:29:02 +00001000 StmtUseSorter(S.getSourceManager()));
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001001
1002 // Classify the current code body for better warning text.
1003 // This enum should stay in sync with the cases in
1004 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1005 // FIXME: Should we use a common classification enum and the same set of
1006 // possibilities all throughout Sema?
1007 enum {
1008 Function,
1009 Method,
1010 Block,
1011 Lambda
1012 } FunctionKind;
1013
1014 if (isa<sema::BlockScopeInfo>(CurFn))
1015 FunctionKind = Block;
1016 else if (isa<sema::LambdaScopeInfo>(CurFn))
1017 FunctionKind = Lambda;
1018 else if (isa<ObjCMethodDecl>(D))
1019 FunctionKind = Method;
1020 else
1021 FunctionKind = Function;
1022
1023 // Iterate through the sorted problems and emit warnings for each.
1024 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1025 E = UsesByStmt.end();
1026 I != E; ++I) {
1027 const Stmt *FirstRead = I->first;
1028 const WeakObjectProfileTy &Key = I->second->first;
1029 const WeakUseVector &Uses = I->second->second;
1030
Jordan Rose7a270482012-09-28 22:21:35 +00001031 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1032 // may not contain enough information to determine that these are different
1033 // properties. We can only be 100% sure of a repeated use in certain cases,
1034 // and we adjust the diagnostic kind accordingly so that the less certain
1035 // case can be turned off if it is too noisy.
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001036 unsigned DiagKind;
1037 if (Key.isExactProfile())
1038 DiagKind = diag::warn_arc_repeated_use_of_weak;
1039 else
1040 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1041
Jordan Rose7a270482012-09-28 22:21:35 +00001042 // Classify the weak object being accessed for better warning text.
1043 // This enum should stay in sync with the cases in
1044 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1045 enum {
1046 Variable,
1047 Property,
1048 ImplicitProperty,
1049 Ivar
1050 } ObjectKind;
1051
1052 const NamedDecl *D = Key.getProperty();
1053 if (isa<VarDecl>(D))
1054 ObjectKind = Variable;
1055 else if (isa<ObjCPropertyDecl>(D))
1056 ObjectKind = Property;
1057 else if (isa<ObjCMethodDecl>(D))
1058 ObjectKind = ImplicitProperty;
1059 else if (isa<ObjCIvarDecl>(D))
1060 ObjectKind = Ivar;
1061 else
1062 llvm_unreachable("Unexpected weak object kind!");
1063
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001064 // Show the first time the object was read.
1065 S.Diag(FirstRead->getLocStart(), DiagKind)
Jordan Rose7a270482012-09-28 22:21:35 +00001066 << ObjectKind << D << FunctionKind
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001067 << FirstRead->getSourceRange();
1068
1069 // Print all the other accesses as notes.
1070 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1071 UI != UE; ++UI) {
1072 if (UI->getUseExpr() == FirstRead)
1073 continue;
1074 S.Diag(UI->getUseExpr()->getLocStart(),
1075 diag::note_arc_weak_also_accessed_here)
1076 << UI->getUseExpr()->getSourceRange();
1077 }
1078 }
1079}
1080
1081
1082namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001083struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +00001084 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001085 // Prefer a more confident report over a less confident one.
1086 if (a.getKind() != b.getKind())
1087 return a.getKind() > b.getKind();
1088 SourceLocation aLoc = a.getUser()->getLocStart();
1089 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001090 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1091 }
1092};
1093
Ted Kremenek610068c2011-01-15 02:58:47 +00001094class UninitValsDiagReporter : public UninitVariablesHandler {
1095 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001096 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek9e761722011-10-13 18:50:06 +00001097 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001098 UsesMap *uses;
1099
Ted Kremenek610068c2011-01-15 02:58:47 +00001100public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001101 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1102 ~UninitValsDiagReporter() {
1103 flushDiagnostics();
1104 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001105
1106 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001107 if (!uses)
1108 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +00001109
1110 UsesMap::mapped_type &V = (*uses)[vd];
1111 UsesVec *&vec = V.first;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001112 if (!vec)
1113 vec = new UsesVec();
1114
Ted Kremenek9e761722011-10-13 18:50:06 +00001115 return V;
1116 }
1117
Richard Smith2815e1a2012-05-25 02:17:09 +00001118 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
1119 getUses(vd).first->push_back(use);
Ted Kremenek9e761722011-10-13 18:50:06 +00001120 }
1121
1122 void handleSelfInit(const VarDecl *vd) {
1123 getUses(vd).second = true;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001124 }
1125
1126 void flushDiagnostics() {
1127 if (!uses)
1128 return;
Ted Kremenek609e3172011-02-02 23:35:53 +00001129
Richard Smith81891882012-05-24 23:45:35 +00001130 // FIXME: This iteration order, and thus the resulting diagnostic order,
1131 // is nondeterministic.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001132 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1133 const VarDecl *vd = i->first;
Ted Kremenek9e761722011-10-13 18:50:06 +00001134 const UsesMap::mapped_type &V = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +00001135
Ted Kremenek9e761722011-10-13 18:50:06 +00001136 UsesVec *vec = V.first;
1137 bool hasSelfInit = V.second;
1138
1139 // Specially handle the case where we have uses of an uninitialized
1140 // variable, but the root cause is an idiomatic self-init. We want
1141 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001142 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith2815e1a2012-05-25 02:17:09 +00001143 DiagnoseUninitializedUse(S, vd,
1144 UninitUse(vd->getInit()->IgnoreParenCasts(),
1145 /* isAlwaysUninit */ true),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001146 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +00001147 else {
1148 // Sort the uses by their SourceLocations. While not strictly
1149 // guaranteed to produce them in line/column order, this will provide
1150 // a stable ordering.
1151 std::sort(vec->begin(), vec->end(), SLocSort());
1152
1153 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1154 ++vi) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001155 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1156 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1157
1158 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek9e761722011-10-13 18:50:06 +00001159 // Skip further diagnostics for this variable. We try to warn only
1160 // on the first point at which a variable is used uninitialized.
1161 break;
1162 }
Chandler Carruth64fb9592011-04-05 18:18:08 +00001163 }
Ted Kremenek9e761722011-10-13 18:50:06 +00001164
1165 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +00001166 delete vec;
1167 }
1168 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +00001169 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001170
1171private:
1172 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1173 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smith2815e1a2012-05-25 02:17:09 +00001174 if (i->getKind() == UninitUse::Always) {
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +00001175 return true;
1176 }
1177 }
1178 return false;
1179}
Ted Kremenek610068c2011-01-15 02:58:47 +00001180};
1181}
1182
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001183
1184//===----------------------------------------------------------------------===//
1185// -Wthread-safety
1186//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001187namespace clang {
1188namespace thread_safety {
Richard Smith2e515622012-02-03 04:45:26 +00001189typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1190typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramerecafd302012-03-26 14:05:40 +00001191typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001192
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001193struct SortDiagBySourceLocation {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001194 SourceManager &SM;
1195 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001196
1197 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1198 // Although this call will be slow, this is only called when outputting
1199 // multiple warnings.
Benjamin Kramerecafd302012-03-26 14:05:40 +00001200 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001201 }
1202};
1203
David Blaikie99ba9e32011-12-20 02:48:34 +00001204namespace {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001205class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1206 Sema &S;
1207 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +00001208 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001209
1210 // Helper functions
1211 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001212 // Gracefully handle rare cases when the analysis can't get a more
1213 // precise source location.
1214 if (!Loc.isValid())
1215 Loc = FunLocation;
Richard Smith2e515622012-02-03 04:45:26 +00001216 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1217 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001218 }
1219
1220 public:
Richard Smith2e515622012-02-03 04:45:26 +00001221 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1222 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001223
1224 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1225 /// We need to output diagnostics produced while iterating through
1226 /// the lockset in deterministic order, so this function orders diagnostics
1227 /// and outputs them.
1228 void emitDiagnostics() {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001229 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001230 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith2e515622012-02-03 04:45:26 +00001231 I != E; ++I) {
1232 S.Diag(I->first.first, I->first.second);
1233 const OptionalNotes &Notes = I->second;
1234 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1235 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1236 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001237 }
1238
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001239 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001240 PartialDiagnosticAt Warning(Loc,
1241 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1242 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001243 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001244 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1245 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1246 }
1247
1248 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1249 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1250 }
1251
Richard Smith2e515622012-02-03 04:45:26 +00001252 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1253 SourceLocation LocEndOfScope,
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001254 LockErrorKind LEK){
1255 unsigned DiagID = 0;
1256 switch (LEK) {
1257 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +00001258 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001259 break;
1260 case LEK_LockedSomeLoopIterations:
1261 DiagID = diag::warn_expecting_lock_held_on_loop;
1262 break;
1263 case LEK_LockedAtEndOfFunction:
1264 DiagID = diag::warn_no_unlock;
1265 break;
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001266 case LEK_NotLockedAtEndOfFunction:
1267 DiagID = diag::warn_expecting_locked;
1268 break;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001269 }
Richard Smith2e515622012-02-03 04:45:26 +00001270 if (LocEndOfScope.isInvalid())
1271 LocEndOfScope = FunEndLocation;
1272
1273 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
1274 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1275 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001276 }
1277
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001278
1279 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1280 SourceLocation Loc2) {
Richard Smith2e515622012-02-03 04:45:26 +00001281 PartialDiagnosticAt Warning(
1282 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1283 PartialDiagnosticAt Note(
1284 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1285 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001286 }
1287
1288 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1289 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +00001290 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1291 && "Only works for variables");
1292 unsigned DiagID = POK == POK_VarAccess?
1293 diag::warn_variable_requires_any_lock:
1294 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +00001295 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001296 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith2e515622012-02-03 04:45:26 +00001297 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001298 }
1299
1300 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001301 Name LockName, LockKind LK, SourceLocation Loc,
1302 Name *PossibleMatch) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +00001303 unsigned DiagID = 0;
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001304 if (PossibleMatch) {
1305 switch (POK) {
1306 case POK_VarAccess:
1307 DiagID = diag::warn_variable_requires_lock_precise;
1308 break;
1309 case POK_VarDereference:
1310 DiagID = diag::warn_var_deref_requires_lock_precise;
1311 break;
1312 case POK_FunctionCall:
1313 DiagID = diag::warn_fun_requires_lock_precise;
1314 break;
1315 }
1316 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001317 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001318 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1319 << *PossibleMatch);
1320 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1321 } else {
1322 switch (POK) {
1323 case POK_VarAccess:
1324 DiagID = diag::warn_variable_requires_lock;
1325 break;
1326 case POK_VarDereference:
1327 DiagID = diag::warn_var_deref_requires_lock;
1328 break;
1329 case POK_FunctionCall:
1330 DiagID = diag::warn_fun_requires_lock;
1331 break;
1332 }
1333 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001334 << D->getNameAsString() << LockName << LK);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001335 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001336 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001337 }
1338
1339 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001340 PartialDiagnosticAt Warning(Loc,
1341 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1342 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001343 }
1344};
1345}
1346}
David Blaikie99ba9e32011-12-20 02:48:34 +00001347}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001348
Ted Kremenek610068c2011-01-15 02:58:47 +00001349//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001350// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1351// warnings on a function, method, or block.
1352//===----------------------------------------------------------------------===//
1353
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001354clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1355 enableCheckFallThrough = 1;
1356 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001357 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001358}
1359
Chandler Carruth5d989942011-07-06 16:21:37 +00001360clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1361 : S(s),
1362 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001363 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001364 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001365 MaxCFGBlocksPerFunction(0),
1366 NumUninitAnalysisFunctions(0),
1367 NumUninitAnalysisVariables(0),
1368 MaxUninitAnalysisVariablesPerFunction(0),
1369 NumUninitAnalysisBlockVisits(0),
1370 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +00001371 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001372 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001373 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001374 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001375 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1376 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001377 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001378
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001379}
1380
Ted Kremenek351ba912011-02-23 01:52:04 +00001381static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001382 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001383 i = fscope->PossiblyUnreachableDiags.begin(),
1384 e = fscope->PossiblyUnreachableDiags.end();
1385 i != e; ++i) {
1386 const sema::PossiblyUnreachableDiag &D = *i;
1387 S.Diag(D.Loc, D.PD);
1388 }
1389}
1390
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001391void clang::sema::
1392AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001393 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001394 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001395
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001396 // We avoid doing analysis-based warnings when there are errors for
1397 // two reasons:
1398 // (1) The CFGs often can't be constructed (if the body is invalid), so
1399 // don't bother trying.
1400 // (2) The code already has problems; running the analysis just takes more
1401 // time.
David Blaikied6471f72011-09-25 23:23:43 +00001402 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +00001403
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001404 // Do not do any analysis for declarations in system headers if we are
1405 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001406 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001407 S.SourceMgr.isInSystemHeader(D->getLocation()))
1408 return;
1409
John McCalle0054f62010-08-25 05:56:39 +00001410 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +00001411 if (cast<DeclContext>(D)->isDependentContext())
1412 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001413
Ted Kremenek351ba912011-02-23 01:52:04 +00001414 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1415 // Flush out any possibly unreachable diagnostics.
1416 flushDiagnostics(S, fscope);
1417 return;
1418 }
1419
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001420 const Stmt *Body = D->getBody();
1421 assert(Body);
1422
Jordy Rosed2001872012-04-28 01:58:08 +00001423 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001424
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001425 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1426 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001427 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1428 AC.getCFGBuildOptions().AddEHEdges = false;
1429 AC.getCFGBuildOptions().AddInitializers = true;
1430 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rosefaadf482012-09-05 23:11:06 +00001431 AC.getCFGBuildOptions().AddTemporaryDtors = true;
1432
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001433 // Force that certain expressions appear as CFGElements in the CFG. This
1434 // is used to speed up various analyses.
1435 // FIXME: This isn't the right factoring. This is here for initial
1436 // prototyping, but we need a way for analyses to say what expressions they
1437 // expect to always be CFGElements and then fill in the BuildOptions
1438 // appropriately. This is essentially a layering violation.
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001439 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
1440 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001441 AC.getCFGBuildOptions().setAllAlwaysAdd();
1442 }
1443 else {
1444 AC.getCFGBuildOptions()
1445 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smith6cfa78f2012-07-17 01:27:33 +00001446 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001447 .setAlwaysAdd(Stmt::BlockExprClass)
1448 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1449 .setAlwaysAdd(Stmt::DeclRefExprClass)
1450 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001451 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1452 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001453 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001454
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001455 // Construct the analysis context with the specified CFG build options.
1456
Ted Kremenek351ba912011-02-23 01:52:04 +00001457 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +00001458 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001459 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001460
1461 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001462 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001463 i = fscope->PossiblyUnreachableDiags.begin(),
1464 e = fscope->PossiblyUnreachableDiags.end();
1465 i != e; ++i) {
1466 if (const Stmt *stmt = i->stmt)
1467 AC.registerForcedBlockExpression(stmt);
1468 }
1469
1470 if (AC.getCFG()) {
1471 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001472 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001473 i = fscope->PossiblyUnreachableDiags.begin(),
1474 e = fscope->PossiblyUnreachableDiags.end();
1475 i != e; ++i)
1476 {
1477 const sema::PossiblyUnreachableDiag &D = *i;
1478 bool processed = false;
1479 if (const Stmt *stmt = i->stmt) {
1480 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +00001481 CFGReverseBlockReachabilityAnalysis *cra =
1482 AC.getCFGReachablityAnalysis();
1483 // FIXME: We should be able to assert that block is non-null, but
1484 // the CFG analysis can skip potentially-evaluated expressions in
1485 // edge cases; see test/Sema/vla-2.c.
1486 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001487 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001488 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001489 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001490 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001491 }
1492 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001493 if (!processed) {
1494 // Emit the warning anyway if we cannot map to a basic block.
1495 S.Diag(D.Loc, D.PD);
1496 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001497 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001498 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001499
1500 if (!analyzed)
1501 flushDiagnostics(S, fscope);
1502 }
1503
1504
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001505 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +00001506 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001507 const CheckFallThroughDiagnostics &CD =
1508 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +00001509 : (isa<CXXMethodDecl>(D) &&
1510 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1511 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1512 ? CheckFallThroughDiagnostics::MakeForLambda()
1513 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001514 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001515 }
1516
1517 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +00001518 if (P.enableCheckUnreachable) {
1519 // Only check for unreachable code on non-template instantiations.
1520 // Different template instantiations can effectively change the control-flow
1521 // and it is very difficult to prove that a snippet of code in a template
1522 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +00001523 bool isTemplateInstantiation = false;
1524 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1525 isTemplateInstantiation = Function->isTemplateInstantiation();
1526 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +00001527 CheckUnreachable(S, AC);
1528 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001529
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001530 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +00001531 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001532 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +00001533 SourceLocation FEL = AC.getDecl()->getLocEnd();
1534 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001535 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1536 Reporter.emitDiagnostics();
1537 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001538
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001539 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001540 != DiagnosticsEngine::Ignored ||
Richard Smith2815e1a2012-05-25 02:17:09 +00001541 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1542 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +00001543 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001544 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001545 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001546 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001547 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001548 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001549 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001550 reporter, stats);
1551
1552 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1553 ++NumUninitAnalysisFunctions;
1554 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1555 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1556 MaxUninitAnalysisVariablesPerFunction =
1557 std::max(MaxUninitAnalysisVariablesPerFunction,
1558 stats.NumVariablesAnalyzed);
1559 MaxUninitAnalysisBlockVisitsPerFunction =
1560 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1561 stats.NumBlockVisits);
1562 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001563 }
1564 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001565
Alexander Kornienko19736342012-06-02 01:01:07 +00001566 bool FallThroughDiagFull =
1567 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1568 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001569 bool FallThroughDiagPerFunction =
1570 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko19736342012-06-02 01:01:07 +00001571 D->getLocStart()) != DiagnosticsEngine::Ignored;
Sean Huntc2f51cf2012-06-15 21:22:05 +00001572 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko19736342012-06-02 01:01:07 +00001573 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001574 }
1575
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001576 if (S.getLangOpts().ObjCARCWeak &&
1577 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1578 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Roseb5cd1222012-10-11 16:10:19 +00001579 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rose58b6bdc2012-09-28 22:21:30 +00001580
Chandler Carruth5d989942011-07-06 16:21:37 +00001581 // Collect statistics about the CFG if it was built.
1582 if (S.CollectStats && AC.isCFGBuilt()) {
1583 ++NumFunctionsAnalyzed;
1584 if (CFG *cfg = AC.getCFG()) {
1585 // If we successfully built a CFG for this context, record some more
1586 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001587 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001588 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001589 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001590 } else {
1591 ++NumFunctionsWithBadCFGs;
1592 }
1593 }
1594}
1595
1596void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1597 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1598
1599 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1600 unsigned AvgCFGBlocksPerFunction =
1601 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1602 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1603 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1604 << " " << NumCFGBlocks << " CFG blocks built.\n"
1605 << " " << AvgCFGBlocksPerFunction
1606 << " average CFG blocks per function.\n"
1607 << " " << MaxCFGBlocksPerFunction
1608 << " max CFG blocks per function.\n";
1609
1610 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1611 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1612 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1613 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1614 llvm::errs() << NumUninitAnalysisFunctions
1615 << " functions analyzed for uninitialiazed variables\n"
1616 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1617 << " " << AvgUninitVariablesPerFunction
1618 << " average variables per function.\n"
1619 << " " << MaxUninitAnalysisVariablesPerFunction
1620 << " max variables per function.\n"
1621 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1622 << " " << AvgUninitBlockVisitsPerFunction
1623 << " average block visits per function.\n"
1624 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1625 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001626}