blob: 2d609001d4e47bdd52a1f51f03c40cefc51dfbac [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"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000024#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000029#include "clang/AST/StmtVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000030#include "clang/Analysis/AnalysisContext.h"
31#include "clang/Analysis/CFG.h"
32#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000033#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000034#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000035#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000036#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000037#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000038#include "llvm/ADT/FoldingSet.h"
39#include "llvm/ADT/ImmutableMap.h"
40#include "llvm/ADT/PostOrderIterator.h"
41#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000042#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000043#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000044#include <algorithm>
45#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000046
47using namespace clang;
48
49//===----------------------------------------------------------------------===//
50// Unreachable code analysis.
51//===----------------------------------------------------------------------===//
52
53namespace {
54 class UnreachableCodeHandler : public reachable_code::Callback {
55 Sema &S;
56 public:
57 UnreachableCodeHandler(Sema &s) : S(s) {}
58
59 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
60 S.Diag(L, diag::warn_unreachable) << R1 << R2;
61 }
62 };
63}
64
65/// CheckUnreachable - Check for unreachable code.
Ted Kremenek1d26f482011-10-24 01:32:45 +000066static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000067 UnreachableCodeHandler UC(S);
68 reachable_code::FindUnreachableCode(AC, UC);
69}
70
71//===----------------------------------------------------------------------===//
72// Check for missing return value.
73//===----------------------------------------------------------------------===//
74
John McCall16565aa2010-05-16 09:34:11 +000075enum ControlFlowKind {
76 UnknownFallThrough,
77 NeverFallThrough,
78 MaybeFallThrough,
79 AlwaysFallThrough,
80 NeverFallThroughOrReturn
81};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000082
83/// CheckFallThrough - Check that we don't fall off the end of a
84/// Statement that should return a value.
85///
86/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
87/// MaybeFallThrough iff we might or might not fall off the end,
88/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
89/// return. We assume NeverFallThrough iff we never fall off the end of the
90/// statement but we may return. We assume that functions not marked noreturn
91/// will return.
Ted Kremenek1d26f482011-10-24 01:32:45 +000092static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000093 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000094 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000095
96 // The CFG leaves in dead things, and we don't want the dead code paths to
97 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000098 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +000099 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000100 live);
101
102 bool AddEHEdges = AC.getAddEHEdges();
103 if (!AddEHEdges && count != cfg->getNumBlockIDs())
104 // When there are things remaining dead, and we didn't add EH edges
105 // from CallExprs to the catch clauses, we have to go back and
106 // mark them as live.
107 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
108 CFGBlock &b = **I;
109 if (!live[b.getBlockID()]) {
110 if (b.pred_begin() == b.pred_end()) {
111 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
112 // When not adding EH edges from calls, catch clauses
113 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000114 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000115 continue;
116 }
117 }
118 }
119
120 // Now we know what is live, we check the live precessors of the exit block
121 // and look for fall through paths, being careful to ignore normal returns,
122 // and exceptional paths.
123 bool HasLiveReturn = false;
124 bool HasFakeEdge = false;
125 bool HasPlainEdge = false;
126 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000127
128 // Ignore default cases that aren't likely to be reachable because all
129 // enums in a switch(X) have explicit case statements.
130 CFGBlock::FilterOptions FO;
131 FO.IgnoreDefaultsWithCoveredEnums = 1;
132
133 for (CFGBlock::filtered_pred_iterator
134 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
135 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000136 if (!live[B.getBlockID()])
137 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000138
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000139 // Skip blocks which contain an element marked as no-return. They don't
140 // represent actually viable edges into the exit block, so mark them as
141 // abnormal.
142 if (B.hasNoReturnElement()) {
143 HasAbnormalEdge = true;
144 continue;
145 }
146
Ted Kremenek5811f592011-01-26 04:49:52 +0000147 // Destructors can appear after the 'return' in the CFG. This is
148 // normal. We need to look pass the destructors for the return
149 // statement (if it exists).
150 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000151
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000152 for ( ; ri != re ; ++ri)
153 if (isa<CFGStmt>(*ri))
Ted Kremenek5811f592011-01-26 04:49:52 +0000154 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000155
Ted Kremenek5811f592011-01-26 04:49:52 +0000156 // No more CFGElements in the block?
157 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000158 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
159 HasAbnormalEdge = true;
160 continue;
161 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000162 // A labeled empty statement, or the entry block...
163 HasPlainEdge = true;
164 continue;
165 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000166
Ted Kremenek5811f592011-01-26 04:49:52 +0000167 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000168 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000169 if (isa<ReturnStmt>(S)) {
170 HasLiveReturn = true;
171 continue;
172 }
173 if (isa<ObjCAtThrowStmt>(S)) {
174 HasFakeEdge = true;
175 continue;
176 }
177 if (isa<CXXThrowExpr>(S)) {
178 HasFakeEdge = true;
179 continue;
180 }
181 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
182 if (AS->isMSAsm()) {
183 HasFakeEdge = true;
184 HasLiveReturn = true;
185 continue;
186 }
187 }
188 if (isa<CXXTryStmt>(S)) {
189 HasAbnormalEdge = true;
190 continue;
191 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000192 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
193 == B.succ_end()) {
194 HasAbnormalEdge = true;
195 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000196 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000197
198 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000199 }
200 if (!HasPlainEdge) {
201 if (HasLiveReturn)
202 return NeverFallThrough;
203 return NeverFallThroughOrReturn;
204 }
205 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
206 return MaybeFallThrough;
207 // This says AlwaysFallThrough for calls to functions that are not marked
208 // noreturn, that don't return. If people would like this warning to be more
209 // accurate, such functions should be marked as noreturn.
210 return AlwaysFallThrough;
211}
212
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000213namespace {
214
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000215struct CheckFallThroughDiagnostics {
216 unsigned diag_MaybeFallThrough_HasNoReturn;
217 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
218 unsigned diag_AlwaysFallThrough_HasNoReturn;
219 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
220 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000221 enum { Function, Block, Lambda } funMode;
222 bool IsLambda;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000223 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000224
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000225 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000226 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000227 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000228 D.diag_MaybeFallThrough_HasNoReturn =
229 diag::warn_falloff_noreturn_function;
230 D.diag_MaybeFallThrough_ReturnsNonVoid =
231 diag::warn_maybe_falloff_nonvoid_function;
232 D.diag_AlwaysFallThrough_HasNoReturn =
233 diag::warn_falloff_noreturn_function;
234 D.diag_AlwaysFallThrough_ReturnsNonVoid =
235 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000236
237 // Don't suggest that virtual functions be marked "noreturn", since they
238 // might be overridden by non-noreturn functions.
239 bool isVirtualMethod = false;
240 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
241 isVirtualMethod = Method->isVirtual();
242
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000243 // Don't suggest that template instantiations be marked "noreturn"
244 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000245 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
246 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000247
248 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000249 D.diag_NeverFallThroughOrReturn =
250 diag::warn_suggest_noreturn_function;
251 else
252 D.diag_NeverFallThroughOrReturn = 0;
253
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000254 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000255 return D;
256 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000257
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000258 static CheckFallThroughDiagnostics MakeForBlock() {
259 CheckFallThroughDiagnostics D;
260 D.diag_MaybeFallThrough_HasNoReturn =
261 diag::err_noreturn_block_has_return_expr;
262 D.diag_MaybeFallThrough_ReturnsNonVoid =
263 diag::err_maybe_falloff_nonvoid_block;
264 D.diag_AlwaysFallThrough_HasNoReturn =
265 diag::err_noreturn_block_has_return_expr;
266 D.diag_AlwaysFallThrough_ReturnsNonVoid =
267 diag::err_falloff_nonvoid_block;
268 D.diag_NeverFallThroughOrReturn =
269 diag::warn_suggest_noreturn_block;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000270 D.funMode = Block;
271 return D;
272 }
273
274 static CheckFallThroughDiagnostics MakeForLambda() {
275 CheckFallThroughDiagnostics D;
276 D.diag_MaybeFallThrough_HasNoReturn =
277 diag::err_noreturn_lambda_has_return_expr;
278 D.diag_MaybeFallThrough_ReturnsNonVoid =
279 diag::warn_maybe_falloff_nonvoid_lambda;
280 D.diag_AlwaysFallThrough_HasNoReturn =
281 diag::err_noreturn_lambda_has_return_expr;
282 D.diag_AlwaysFallThrough_ReturnsNonVoid =
283 diag::warn_falloff_nonvoid_lambda;
284 D.diag_NeverFallThroughOrReturn = 0;
285 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000286 return D;
287 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000288
David Blaikied6471f72011-09-25 23:23:43 +0000289 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000290 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000291 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000292 return (ReturnsVoid ||
293 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000294 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000295 && (!HasNoReturn ||
296 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000297 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000298 && (!ReturnsVoid ||
299 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000300 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000301 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000302
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000303 // For blocks / lambdas.
304 return ReturnsVoid && !HasNoReturn
305 && ((funMode == Lambda) ||
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000306 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000307 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000308 }
309};
310
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000311}
312
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000313/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
314/// function that should return a value. Check that we don't fall off the end
315/// of a noreturn function. We assume that functions and blocks not marked
316/// noreturn will return.
317static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000318 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000319 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000320 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000321
322 bool ReturnsVoid = false;
323 bool HasNoReturn = false;
324
325 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
326 ReturnsVoid = FD->getResultType()->isVoidType();
327 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000328 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000329 }
330 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
331 ReturnsVoid = MD->getResultType()->isVoidType();
332 HasNoReturn = MD->hasAttr<NoReturnAttr>();
333 }
334 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000335 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000336 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000337 BlockTy->getPointeeType()->getAs<FunctionType>()) {
338 if (FT->getResultType()->isVoidType())
339 ReturnsVoid = true;
340 if (FT->getNoReturnAttr())
341 HasNoReturn = true;
342 }
343 }
344
David Blaikied6471f72011-09-25 23:23:43 +0000345 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000346
347 // Short circuit for compilation speed.
348 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
349 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000350
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000351 // FIXME: Function try block
352 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
353 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000354 case UnknownFallThrough:
355 break;
356
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000357 case MaybeFallThrough:
358 if (HasNoReturn)
359 S.Diag(Compound->getRBracLoc(),
360 CD.diag_MaybeFallThrough_HasNoReturn);
361 else if (!ReturnsVoid)
362 S.Diag(Compound->getRBracLoc(),
363 CD.diag_MaybeFallThrough_ReturnsNonVoid);
364 break;
365 case AlwaysFallThrough:
366 if (HasNoReturn)
367 S.Diag(Compound->getRBracLoc(),
368 CD.diag_AlwaysFallThrough_HasNoReturn);
369 else if (!ReturnsVoid)
370 S.Diag(Compound->getRBracLoc(),
371 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
372 break;
373 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000374 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
375 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
376 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000377 << 0 << FD;
378 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
379 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
380 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000381 } else {
382 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
383 }
384 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000385 break;
386 case NeverFallThrough:
387 break;
388 }
389 }
390}
391
392//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000393// -Wuninitialized
394//===----------------------------------------------------------------------===//
395
Ted Kremenek6f417152011-04-04 20:56:00 +0000396namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000397/// ContainsReference - A visitor class to search for references to
398/// a particular declaration (the needle) within any evaluated component of an
399/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000400class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000401 bool FoundReference;
402 const DeclRefExpr *Needle;
403
Ted Kremenek6f417152011-04-04 20:56:00 +0000404public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000405 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
406 : EvaluatedExprVisitor<ContainsReference>(Context),
407 FoundReference(false), Needle(Needle) {}
408
409 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000410 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000411 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000412 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000413
414 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000415 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000416
417 void VisitDeclRefExpr(DeclRefExpr *E) {
418 if (E == Needle)
419 FoundReference = true;
420 else
421 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000422 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000423
424 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000425};
426}
427
David Blaikie4f4f3492011-09-10 05:35:08 +0000428static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
429 // Don't issue a fixit if there is already an initializer.
430 if (VD->getInit())
431 return false;
432
433 // Suggest possible initialization (if any).
David Blaikie4f4f3492011-09-10 05:35:08 +0000434 QualType VariableTy = VD->getType().getCanonicalType();
Richard Smith7984de32012-01-12 23:53:29 +0000435 const char *Init = S.getFixItZeroInitializerForType(VariableTy);
436 if (!Init)
David Blaikie4f4f3492011-09-10 05:35:08 +0000437 return false;
David Blaikie4f4f3492011-09-10 05:35:08 +0000438
Richard Smith7984de32012-01-12 23:53:29 +0000439 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
440 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
441 << FixItHint::CreateInsertion(Loc, Init);
442 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000443}
444
Chandler Carruth262d50e2011-04-05 18:27:05 +0000445/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
446/// uninitialized variable. This manages the different forms of diagnostic
447/// emitted for particular types of uses. Returns true if the use was diagnosed
448/// as a warning. If a pariticular use is one we omit warnings for, returns
449/// false.
450static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Ted Kremenek9e761722011-10-13 18:50:06 +0000451 const Expr *E, bool isAlwaysUninit,
452 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000453 bool isSelfInit = false;
454
455 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
456 if (isAlwaysUninit) {
457 // Inspect the initializer of the variable declaration which is
458 // being referenced prior to its initialization. We emit
459 // specialized diagnostics for self-initialization, and we
460 // specifically avoid warning about self references which take the
461 // form of:
462 //
463 // int x = x;
464 //
465 // This is used to indicate to GCC that 'x' is intentionally left
466 // uninitialized. Proven code paths which access 'x' in
467 // an uninitialized state after this will still warn.
468 //
469 // TODO: Should we suppress maybe-uninitialized warnings for
470 // variables initialized in this way?
471 if (const Expr *Initializer = VD->getInit()) {
Ted Kremenek9e761722011-10-13 18:50:06 +0000472 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000473 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000474
475 ContainsReference CR(S.Context, DRE);
476 CR.Visit(const_cast<Expr*>(Initializer));
477 isSelfInit = CR.doesContainReference();
478 }
479 if (isSelfInit) {
480 S.Diag(DRE->getLocStart(),
481 diag::warn_uninit_self_reference_in_init)
482 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
483 } else {
484 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
485 << VD->getDeclName() << DRE->getSourceRange();
486 }
487 } else {
488 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
489 << VD->getDeclName() << DRE->getSourceRange();
490 }
491 } else {
492 const BlockExpr *BE = cast<BlockExpr>(E);
493 S.Diag(BE->getLocStart(),
494 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
495 : diag::warn_maybe_uninit_var_captured_by_block)
496 << VD->getDeclName();
497 }
498
499 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000500 // the initializer of that declaration & we didn't already suggest
501 // an initialization fixit.
502 if (!isSelfInit && !SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000503 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
504 << VD->getDeclName();
505
Chandler Carruth262d50e2011-04-05 18:27:05 +0000506 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000507}
508
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000509typedef std::pair<const Expr*, bool> UninitUse;
510
Ted Kremenek610068c2011-01-15 02:58:47 +0000511namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000512struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000513 bool operator()(const UninitUse &a, const UninitUse &b) {
514 SourceLocation aLoc = a.first->getLocStart();
515 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000516 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
517 }
518};
519
Ted Kremenek610068c2011-01-15 02:58:47 +0000520class UninitValsDiagReporter : public UninitVariablesHandler {
521 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000522 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek9e761722011-10-13 18:50:06 +0000523 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000524 UsesMap *uses;
525
Ted Kremenek610068c2011-01-15 02:58:47 +0000526public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000527 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
528 ~UninitValsDiagReporter() {
529 flushDiagnostics();
530 }
Ted Kremenek9e761722011-10-13 18:50:06 +0000531
532 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000533 if (!uses)
534 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +0000535
536 UsesMap::mapped_type &V = (*uses)[vd];
537 UsesVec *&vec = V.first;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000538 if (!vec)
539 vec = new UsesVec();
540
Ted Kremenek9e761722011-10-13 18:50:06 +0000541 return V;
542 }
543
544 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
545 bool isAlwaysUninit) {
546 getUses(vd).first->push_back(std::make_pair(ex, isAlwaysUninit));
547 }
548
549 void handleSelfInit(const VarDecl *vd) {
550 getUses(vd).second = true;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000551 }
552
553 void flushDiagnostics() {
554 if (!uses)
555 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000556
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000557 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
558 const VarDecl *vd = i->first;
Ted Kremenek9e761722011-10-13 18:50:06 +0000559 const UsesMap::mapped_type &V = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000560
Ted Kremenek9e761722011-10-13 18:50:06 +0000561 UsesVec *vec = V.first;
562 bool hasSelfInit = V.second;
563
564 // Specially handle the case where we have uses of an uninitialized
565 // variable, but the root cause is an idiomatic self-init. We want
566 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000567 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Ted Kremenek9e761722011-10-13 18:50:06 +0000568 DiagnoseUninitializedUse(S, vd, vd->getInit()->IgnoreParenCasts(),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000569 /* isAlwaysUninit */ true,
570 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +0000571 else {
572 // Sort the uses by their SourceLocations. While not strictly
573 // guaranteed to produce them in line/column order, this will provide
574 // a stable ordering.
575 std::sort(vec->begin(), vec->end(), SLocSort());
576
577 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
578 ++vi) {
579 if (DiagnoseUninitializedUse(S, vd, vi->first,
580 /*isAlwaysUninit=*/vi->second))
581 // Skip further diagnostics for this variable. We try to warn only
582 // on the first point at which a variable is used uninitialized.
583 break;
584 }
Chandler Carruth64fb9592011-04-05 18:18:08 +0000585 }
Ted Kremenek9e761722011-10-13 18:50:06 +0000586
587 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000588 delete vec;
589 }
590 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000591 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000592
593private:
594 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
595 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
596 if (i->second) {
597 return true;
598 }
599 }
600 return false;
601}
Ted Kremenek610068c2011-01-15 02:58:47 +0000602};
603}
604
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000605
606//===----------------------------------------------------------------------===//
607// -Wthread-safety
608//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000609namespace clang {
610namespace thread_safety {
Richard Smith2e515622012-02-03 04:45:26 +0000611typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
612typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000613typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
614
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000615struct SortDiagBySourceLocation {
616 Sema &S;
617 SortDiagBySourceLocation(Sema &S) : S(S) {}
618
619 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
620 // Although this call will be slow, this is only called when outputting
621 // multiple warnings.
Richard Smith2e515622012-02-03 04:45:26 +0000622 return S.getSourceManager().isBeforeInTranslationUnit(left.first.first,
623 right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000624 }
625};
626
David Blaikie99ba9e32011-12-20 02:48:34 +0000627namespace {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000628class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
629 Sema &S;
630 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +0000631 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000632
633 // Helper functions
634 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000635 // Gracefully handle rare cases when the analysis can't get a more
636 // precise source location.
637 if (!Loc.isValid())
638 Loc = FunLocation;
Richard Smith2e515622012-02-03 04:45:26 +0000639 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
640 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000641 }
642
643 public:
Richard Smith2e515622012-02-03 04:45:26 +0000644 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
645 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000646
647 /// \brief Emit all buffered diagnostics in order of sourcelocation.
648 /// We need to output diagnostics produced while iterating through
649 /// the lockset in deterministic order, so this function orders diagnostics
650 /// and outputs them.
651 void emitDiagnostics() {
652 SortDiagBySourceLocation SortDiagBySL(S);
653 sort(Warnings.begin(), Warnings.end(), SortDiagBySL);
654 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith2e515622012-02-03 04:45:26 +0000655 I != E; ++I) {
656 S.Diag(I->first.first, I->first.second);
657 const OptionalNotes &Notes = I->second;
658 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
659 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
660 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000661 }
662
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000663 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +0000664 PartialDiagnosticAt Warning(Loc,
665 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
666 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000667 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000668 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
669 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
670 }
671
672 void handleDoubleLock(Name LockName, SourceLocation Loc) {
673 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
674 }
675
Richard Smith2e515622012-02-03 04:45:26 +0000676 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
677 SourceLocation LocEndOfScope,
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000678 LockErrorKind LEK){
679 unsigned DiagID = 0;
680 switch (LEK) {
681 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +0000682 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000683 break;
684 case LEK_LockedSomeLoopIterations:
685 DiagID = diag::warn_expecting_lock_held_on_loop;
686 break;
687 case LEK_LockedAtEndOfFunction:
688 DiagID = diag::warn_no_unlock;
689 break;
690 }
Richard Smith2e515622012-02-03 04:45:26 +0000691 if (LocEndOfScope.isInvalid())
692 LocEndOfScope = FunEndLocation;
693
694 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
695 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
696 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000697 }
698
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000699
700 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
701 SourceLocation Loc2) {
Richard Smith2e515622012-02-03 04:45:26 +0000702 PartialDiagnosticAt Warning(
703 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
704 PartialDiagnosticAt Note(
705 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
706 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000707 }
708
709 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
710 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +0000711 assert((POK == POK_VarAccess || POK == POK_VarDereference)
712 && "Only works for variables");
713 unsigned DiagID = POK == POK_VarAccess?
714 diag::warn_variable_requires_any_lock:
715 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +0000716 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
717 << D->getName() << getLockKindFromAccessKind(AK));
718 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000719 }
720
721 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
722 Name LockName, LockKind LK, SourceLocation Loc) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +0000723 unsigned DiagID = 0;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000724 switch (POK) {
725 case POK_VarAccess:
726 DiagID = diag::warn_variable_requires_lock;
727 break;
728 case POK_VarDereference:
729 DiagID = diag::warn_var_deref_requires_lock;
730 break;
731 case POK_FunctionCall:
732 DiagID = diag::warn_fun_requires_lock;
733 break;
734 }
Richard Smith2e515622012-02-03 04:45:26 +0000735 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
736 << D->getName() << LockName << LK);
737 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000738 }
739
740 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +0000741 PartialDiagnosticAt Warning(Loc,
742 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
743 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000744 }
745};
746}
747}
David Blaikie99ba9e32011-12-20 02:48:34 +0000748}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000749
Ted Kremenek610068c2011-01-15 02:58:47 +0000750//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000751// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
752// warnings on a function, method, or block.
753//===----------------------------------------------------------------------===//
754
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000755clang::sema::AnalysisBasedWarnings::Policy::Policy() {
756 enableCheckFallThrough = 1;
757 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000758 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000759}
760
Chandler Carruth5d989942011-07-06 16:21:37 +0000761clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
762 : S(s),
763 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000764 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +0000765 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000766 MaxCFGBlocksPerFunction(0),
767 NumUninitAnalysisFunctions(0),
768 NumUninitAnalysisVariables(0),
769 MaxUninitAnalysisVariablesPerFunction(0),
770 NumUninitAnalysisBlockVisits(0),
771 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +0000772 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000773 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000774 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +0000775 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000776 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
777 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +0000778 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000779
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000780}
781
Ted Kremenek351ba912011-02-23 01:52:04 +0000782static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000783 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +0000784 i = fscope->PossiblyUnreachableDiags.begin(),
785 e = fscope->PossiblyUnreachableDiags.end();
786 i != e; ++i) {
787 const sema::PossiblyUnreachableDiag &D = *i;
788 S.Diag(D.Loc, D.PD);
789 }
790}
791
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000792void clang::sema::
793AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000794 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000795 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000796
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000797 // We avoid doing analysis-based warnings when there are errors for
798 // two reasons:
799 // (1) The CFGs often can't be constructed (if the body is invalid), so
800 // don't bother trying.
801 // (2) The code already has problems; running the analysis just takes more
802 // time.
David Blaikied6471f72011-09-25 23:23:43 +0000803 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +0000804
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000805 // Do not do any analysis for declarations in system headers if we are
806 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000807 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000808 S.SourceMgr.isInSystemHeader(D->getLocation()))
809 return;
810
John McCalle0054f62010-08-25 05:56:39 +0000811 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +0000812 if (cast<DeclContext>(D)->isDependentContext())
813 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000814
Ted Kremenek351ba912011-02-23 01:52:04 +0000815 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
816 // Flush out any possibly unreachable diagnostics.
817 flushDiagnostics(S, fscope);
818 return;
819 }
820
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000821 const Stmt *Body = D->getBody();
822 assert(Body);
823
Ted Kremenek1d26f482011-10-24 01:32:45 +0000824 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D, 0);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000825
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000826 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
827 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000828 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
829 AC.getCFGBuildOptions().AddEHEdges = false;
830 AC.getCFGBuildOptions().AddInitializers = true;
831 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000832
833 // Force that certain expressions appear as CFGElements in the CFG. This
834 // is used to speed up various analyses.
835 // FIXME: This isn't the right factoring. This is here for initial
836 // prototyping, but we need a way for analyses to say what expressions they
837 // expect to always be CFGElements and then fill in the BuildOptions
838 // appropriately. This is essentially a layering violation.
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000839 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
840 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000841 AC.getCFGBuildOptions().setAllAlwaysAdd();
842 }
843 else {
844 AC.getCFGBuildOptions()
845 .setAlwaysAdd(Stmt::BinaryOperatorClass)
846 .setAlwaysAdd(Stmt::BlockExprClass)
847 .setAlwaysAdd(Stmt::CStyleCastExprClass)
848 .setAlwaysAdd(Stmt::DeclRefExprClass)
849 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
850 .setAlwaysAdd(Stmt::UnaryOperatorClass);
851 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000852
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000853 // Construct the analysis context with the specified CFG build options.
854
Ted Kremenek351ba912011-02-23 01:52:04 +0000855 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +0000856 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000857 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000858
859 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000860 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000861 i = fscope->PossiblyUnreachableDiags.begin(),
862 e = fscope->PossiblyUnreachableDiags.end();
863 i != e; ++i) {
864 if (const Stmt *stmt = i->stmt)
865 AC.registerForcedBlockExpression(stmt);
866 }
867
868 if (AC.getCFG()) {
869 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000870 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000871 i = fscope->PossiblyUnreachableDiags.begin(),
872 e = fscope->PossiblyUnreachableDiags.end();
873 i != e; ++i)
874 {
875 const sema::PossiblyUnreachableDiag &D = *i;
876 bool processed = false;
877 if (const Stmt *stmt = i->stmt) {
878 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +0000879 CFGReverseBlockReachabilityAnalysis *cra =
880 AC.getCFGReachablityAnalysis();
881 // FIXME: We should be able to assert that block is non-null, but
882 // the CFG analysis can skip potentially-evaluated expressions in
883 // edge cases; see test/Sema/vla-2.c.
884 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000885 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000886 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000887 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000888 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000889 }
890 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000891 if (!processed) {
892 // Emit the warning anyway if we cannot map to a basic block.
893 S.Diag(D.Loc, D.PD);
894 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000895 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000896 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000897
898 if (!analyzed)
899 flushDiagnostics(S, fscope);
900 }
901
902
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000903 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +0000904 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000905 const CheckFallThroughDiagnostics &CD =
906 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000907 : (isa<CXXMethodDecl>(D) &&
908 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
909 cast<CXXMethodDecl>(D)->getParent()->isLambda())
910 ? CheckFallThroughDiagnostics::MakeForLambda()
911 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000912 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000913 }
914
915 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +0000916 if (P.enableCheckUnreachable) {
917 // Only check for unreachable code on non-template instantiations.
918 // Different template instantiations can effectively change the control-flow
919 // and it is very difficult to prove that a snippet of code in a template
920 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000921 bool isTemplateInstantiation = false;
922 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
923 isTemplateInstantiation = Function->isTemplateInstantiation();
924 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +0000925 CheckUnreachable(S, AC);
926 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000927
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000928 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +0000929 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000930 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +0000931 SourceLocation FEL = AC.getDecl()->getLocEnd();
932 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000933 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
934 Reporter.emitDiagnostics();
935 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000936
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000937 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +0000938 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +0000939 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +0000940 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000941 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000942 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +0000943 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +0000944 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000945 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +0000946 reporter, stats);
947
948 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
949 ++NumUninitAnalysisFunctions;
950 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
951 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
952 MaxUninitAnalysisVariablesPerFunction =
953 std::max(MaxUninitAnalysisVariablesPerFunction,
954 stats.NumVariablesAnalyzed);
955 MaxUninitAnalysisBlockVisitsPerFunction =
956 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
957 stats.NumBlockVisits);
958 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000959 }
960 }
Chandler Carruth5d989942011-07-06 16:21:37 +0000961
962 // Collect statistics about the CFG if it was built.
963 if (S.CollectStats && AC.isCFGBuilt()) {
964 ++NumFunctionsAnalyzed;
965 if (CFG *cfg = AC.getCFG()) {
966 // If we successfully built a CFG for this context, record some more
967 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000968 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +0000969 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000970 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +0000971 } else {
972 ++NumFunctionsWithBadCFGs;
973 }
974 }
975}
976
977void clang::sema::AnalysisBasedWarnings::PrintStats() const {
978 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
979
980 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
981 unsigned AvgCFGBlocksPerFunction =
982 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
983 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
984 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
985 << " " << NumCFGBlocks << " CFG blocks built.\n"
986 << " " << AvgCFGBlocksPerFunction
987 << " average CFG blocks per function.\n"
988 << " " << MaxCFGBlocksPerFunction
989 << " max CFG blocks per function.\n";
990
991 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
992 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
993 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
994 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
995 llvm::errs() << NumUninitAnalysisFunctions
996 << " functions analyzed for uninitialiazed variables\n"
997 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
998 << " " << AvgUninitVariablesPerFunction
999 << " average variables per function.\n"
1000 << " " << MaxUninitAnalysisVariablesPerFunction
1001 << " max variables per function.\n"
1002 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1003 << " " << AvgUninitBlockVisitsPerFunction
1004 << " average block visits per function.\n"
1005 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1006 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001007}