blob: c3b802e4db46efbbfe707d703ee288da45fce2da [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;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000222 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000223
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000224 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000225 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000226 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000227 D.diag_MaybeFallThrough_HasNoReturn =
228 diag::warn_falloff_noreturn_function;
229 D.diag_MaybeFallThrough_ReturnsNonVoid =
230 diag::warn_maybe_falloff_nonvoid_function;
231 D.diag_AlwaysFallThrough_HasNoReturn =
232 diag::warn_falloff_noreturn_function;
233 D.diag_AlwaysFallThrough_ReturnsNonVoid =
234 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000235
236 // Don't suggest that virtual functions be marked "noreturn", since they
237 // might be overridden by non-noreturn functions.
238 bool isVirtualMethod = false;
239 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
240 isVirtualMethod = Method->isVirtual();
241
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000242 // Don't suggest that template instantiations be marked "noreturn"
243 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000244 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
245 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000246
247 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000248 D.diag_NeverFallThroughOrReturn =
249 diag::warn_suggest_noreturn_function;
250 else
251 D.diag_NeverFallThroughOrReturn = 0;
252
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000253 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000254 return D;
255 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000256
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000257 static CheckFallThroughDiagnostics MakeForBlock() {
258 CheckFallThroughDiagnostics D;
259 D.diag_MaybeFallThrough_HasNoReturn =
260 diag::err_noreturn_block_has_return_expr;
261 D.diag_MaybeFallThrough_ReturnsNonVoid =
262 diag::err_maybe_falloff_nonvoid_block;
263 D.diag_AlwaysFallThrough_HasNoReturn =
264 diag::err_noreturn_block_has_return_expr;
265 D.diag_AlwaysFallThrough_ReturnsNonVoid =
266 diag::err_falloff_nonvoid_block;
267 D.diag_NeverFallThroughOrReturn =
268 diag::warn_suggest_noreturn_block;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000269 D.funMode = Block;
270 return D;
271 }
272
273 static CheckFallThroughDiagnostics MakeForLambda() {
274 CheckFallThroughDiagnostics D;
275 D.diag_MaybeFallThrough_HasNoReturn =
276 diag::err_noreturn_lambda_has_return_expr;
277 D.diag_MaybeFallThrough_ReturnsNonVoid =
278 diag::warn_maybe_falloff_nonvoid_lambda;
279 D.diag_AlwaysFallThrough_HasNoReturn =
280 diag::err_noreturn_lambda_has_return_expr;
281 D.diag_AlwaysFallThrough_ReturnsNonVoid =
282 diag::warn_falloff_nonvoid_lambda;
283 D.diag_NeverFallThroughOrReturn = 0;
284 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000285 return D;
286 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000287
David Blaikied6471f72011-09-25 23:23:43 +0000288 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000289 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000290 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000291 return (ReturnsVoid ||
292 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000293 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000294 && (!HasNoReturn ||
295 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000296 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000297 && (!ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000299 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000300 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000301
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000302 // For blocks / lambdas.
303 return ReturnsVoid && !HasNoReturn
304 && ((funMode == Lambda) ||
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000305 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000306 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000307 }
308};
309
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000310}
311
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000312/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
313/// function that should return a value. Check that we don't fall off the end
314/// of a noreturn function. We assume that functions and blocks not marked
315/// noreturn will return.
316static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000317 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000318 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000319 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000320
321 bool ReturnsVoid = false;
322 bool HasNoReturn = false;
323
324 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
325 ReturnsVoid = FD->getResultType()->isVoidType();
326 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000327 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000328 }
329 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
330 ReturnsVoid = MD->getResultType()->isVoidType();
331 HasNoReturn = MD->hasAttr<NoReturnAttr>();
332 }
333 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000334 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000335 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000336 BlockTy->getPointeeType()->getAs<FunctionType>()) {
337 if (FT->getResultType()->isVoidType())
338 ReturnsVoid = true;
339 if (FT->getNoReturnAttr())
340 HasNoReturn = true;
341 }
342 }
343
David Blaikied6471f72011-09-25 23:23:43 +0000344 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000345
346 // Short circuit for compilation speed.
347 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
348 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000349
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000350 // FIXME: Function try block
351 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
352 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000353 case UnknownFallThrough:
354 break;
355
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000356 case MaybeFallThrough:
357 if (HasNoReturn)
358 S.Diag(Compound->getRBracLoc(),
359 CD.diag_MaybeFallThrough_HasNoReturn);
360 else if (!ReturnsVoid)
361 S.Diag(Compound->getRBracLoc(),
362 CD.diag_MaybeFallThrough_ReturnsNonVoid);
363 break;
364 case AlwaysFallThrough:
365 if (HasNoReturn)
366 S.Diag(Compound->getRBracLoc(),
367 CD.diag_AlwaysFallThrough_HasNoReturn);
368 else if (!ReturnsVoid)
369 S.Diag(Compound->getRBracLoc(),
370 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
371 break;
372 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000373 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
374 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
375 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000376 << 0 << FD;
377 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
378 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
379 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000380 } else {
381 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
382 }
383 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000384 break;
385 case NeverFallThrough:
386 break;
387 }
388 }
389}
390
391//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000392// -Wuninitialized
393//===----------------------------------------------------------------------===//
394
Ted Kremenek6f417152011-04-04 20:56:00 +0000395namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000396/// ContainsReference - A visitor class to search for references to
397/// a particular declaration (the needle) within any evaluated component of an
398/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000399class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000400 bool FoundReference;
401 const DeclRefExpr *Needle;
402
Ted Kremenek6f417152011-04-04 20:56:00 +0000403public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000404 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
405 : EvaluatedExprVisitor<ContainsReference>(Context),
406 FoundReference(false), Needle(Needle) {}
407
408 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000409 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000410 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000411 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000412
413 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000414 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000415
416 void VisitDeclRefExpr(DeclRefExpr *E) {
417 if (E == Needle)
418 FoundReference = true;
419 else
420 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000421 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000422
423 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000424};
425}
426
David Blaikie4f4f3492011-09-10 05:35:08 +0000427static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000428 QualType VariableTy = VD->getType().getCanonicalType();
429 if (VariableTy->isBlockPointerType() &&
430 !VD->hasAttr<BlocksAttr>()) {
431 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
432 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
433 return true;
434 }
435
David Blaikie4f4f3492011-09-10 05:35:08 +0000436 // Don't issue a fixit if there is already an initializer.
437 if (VD->getInit())
438 return false;
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000439
David Blaikie4f4f3492011-09-10 05:35:08 +0000440 // Suggest possible initialization (if any).
David Blaikie2c0abf42012-04-30 18:27:22 +0000441 std::string Init = S.getFixItZeroInitializerForType(VariableTy);
442 if (Init.empty())
David Blaikie4f4f3492011-09-10 05:35:08 +0000443 return false;
Richard Trieu7b0a3e32012-05-03 01:09:59 +0000444
445 // Don't suggest a fixit inside macros.
446 if (VD->getLocEnd().isMacroID())
447 return false;
448
Richard Smith7984de32012-01-12 23:53:29 +0000449 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000450
Richard Smith7984de32012-01-12 23:53:29 +0000451 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
452 << FixItHint::CreateInsertion(Loc, Init);
453 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000454}
455
Chandler Carruth262d50e2011-04-05 18:27:05 +0000456/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
457/// uninitialized variable. This manages the different forms of diagnostic
458/// emitted for particular types of uses. Returns true if the use was diagnosed
459/// as a warning. If a pariticular use is one we omit warnings for, returns
460/// false.
461static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Ted Kremenek9e761722011-10-13 18:50:06 +0000462 const Expr *E, bool isAlwaysUninit,
463 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000464 bool isSelfInit = false;
465
466 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
467 if (isAlwaysUninit) {
468 // Inspect the initializer of the variable declaration which is
469 // being referenced prior to its initialization. We emit
470 // specialized diagnostics for self-initialization, and we
471 // specifically avoid warning about self references which take the
472 // form of:
473 //
474 // int x = x;
475 //
476 // This is used to indicate to GCC that 'x' is intentionally left
477 // uninitialized. Proven code paths which access 'x' in
478 // an uninitialized state after this will still warn.
479 //
480 // TODO: Should we suppress maybe-uninitialized warnings for
481 // variables initialized in this way?
482 if (const Expr *Initializer = VD->getInit()) {
Ted Kremenek9e761722011-10-13 18:50:06 +0000483 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000484 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000485
486 ContainsReference CR(S.Context, DRE);
487 CR.Visit(const_cast<Expr*>(Initializer));
488 isSelfInit = CR.doesContainReference();
489 }
490 if (isSelfInit) {
491 S.Diag(DRE->getLocStart(),
492 diag::warn_uninit_self_reference_in_init)
493 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
494 } else {
495 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
496 << VD->getDeclName() << DRE->getSourceRange();
497 }
498 } else {
499 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
500 << VD->getDeclName() << DRE->getSourceRange();
501 }
502 } else {
503 const BlockExpr *BE = cast<BlockExpr>(E);
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000504 if (VD->getType()->isBlockPointerType() &&
505 !VD->hasAttr<BlocksAttr>())
506 S.Diag(BE->getLocStart(), diag::warn_uninit_byref_blockvar_captured_by_block)
507 << VD->getDeclName();
508 else
509 S.Diag(BE->getLocStart(),
510 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
511 : diag::warn_maybe_uninit_var_captured_by_block)
512 << VD->getDeclName();
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000513 }
514
515 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000516 // the initializer of that declaration & we didn't already suggest
517 // an initialization fixit.
518 if (!isSelfInit && !SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000519 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
520 << VD->getDeclName();
521
Chandler Carruth262d50e2011-04-05 18:27:05 +0000522 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000523}
524
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000525typedef std::pair<const Expr*, bool> UninitUse;
526
Ted Kremenek610068c2011-01-15 02:58:47 +0000527namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000528struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000529 bool operator()(const UninitUse &a, const UninitUse &b) {
530 SourceLocation aLoc = a.first->getLocStart();
531 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000532 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
533 }
534};
535
Ted Kremenek610068c2011-01-15 02:58:47 +0000536class UninitValsDiagReporter : public UninitVariablesHandler {
537 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000538 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek9e761722011-10-13 18:50:06 +0000539 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000540 UsesMap *uses;
541
Ted Kremenek610068c2011-01-15 02:58:47 +0000542public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000543 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
544 ~UninitValsDiagReporter() {
545 flushDiagnostics();
546 }
Ted Kremenek9e761722011-10-13 18:50:06 +0000547
548 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000549 if (!uses)
550 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +0000551
552 UsesMap::mapped_type &V = (*uses)[vd];
553 UsesVec *&vec = V.first;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000554 if (!vec)
555 vec = new UsesVec();
556
Ted Kremenek9e761722011-10-13 18:50:06 +0000557 return V;
558 }
559
560 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
561 bool isAlwaysUninit) {
562 getUses(vd).first->push_back(std::make_pair(ex, isAlwaysUninit));
563 }
564
565 void handleSelfInit(const VarDecl *vd) {
566 getUses(vd).second = true;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000567 }
568
569 void flushDiagnostics() {
570 if (!uses)
571 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000572
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000573 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
574 const VarDecl *vd = i->first;
Ted Kremenek9e761722011-10-13 18:50:06 +0000575 const UsesMap::mapped_type &V = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000576
Ted Kremenek9e761722011-10-13 18:50:06 +0000577 UsesVec *vec = V.first;
578 bool hasSelfInit = V.second;
579
580 // Specially handle the case where we have uses of an uninitialized
581 // variable, but the root cause is an idiomatic self-init. We want
582 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000583 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Ted Kremenek9e761722011-10-13 18:50:06 +0000584 DiagnoseUninitializedUse(S, vd, vd->getInit()->IgnoreParenCasts(),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000585 /* isAlwaysUninit */ true,
586 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +0000587 else {
588 // Sort the uses by their SourceLocations. While not strictly
589 // guaranteed to produce them in line/column order, this will provide
590 // a stable ordering.
591 std::sort(vec->begin(), vec->end(), SLocSort());
592
593 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
594 ++vi) {
595 if (DiagnoseUninitializedUse(S, vd, vi->first,
596 /*isAlwaysUninit=*/vi->second))
597 // Skip further diagnostics for this variable. We try to warn only
598 // on the first point at which a variable is used uninitialized.
599 break;
600 }
Chandler Carruth64fb9592011-04-05 18:18:08 +0000601 }
Ted Kremenek9e761722011-10-13 18:50:06 +0000602
603 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000604 delete vec;
605 }
606 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000607 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000608
609private:
610 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
611 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
612 if (i->second) {
613 return true;
614 }
615 }
616 return false;
617}
Ted Kremenek610068c2011-01-15 02:58:47 +0000618};
619}
620
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000621
622//===----------------------------------------------------------------------===//
623// -Wthread-safety
624//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000625namespace clang {
626namespace thread_safety {
Richard Smith2e515622012-02-03 04:45:26 +0000627typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
628typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramerecafd302012-03-26 14:05:40 +0000629typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000630
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000631struct SortDiagBySourceLocation {
Benjamin Kramerecafd302012-03-26 14:05:40 +0000632 SourceManager &SM;
633 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000634
635 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
636 // Although this call will be slow, this is only called when outputting
637 // multiple warnings.
Benjamin Kramerecafd302012-03-26 14:05:40 +0000638 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000639 }
640};
641
David Blaikie99ba9e32011-12-20 02:48:34 +0000642namespace {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000643class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
644 Sema &S;
645 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +0000646 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000647
648 // Helper functions
649 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000650 // Gracefully handle rare cases when the analysis can't get a more
651 // precise source location.
652 if (!Loc.isValid())
653 Loc = FunLocation;
Richard Smith2e515622012-02-03 04:45:26 +0000654 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
655 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000656 }
657
658 public:
Richard Smith2e515622012-02-03 04:45:26 +0000659 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
660 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000661
662 /// \brief Emit all buffered diagnostics in order of sourcelocation.
663 /// We need to output diagnostics produced while iterating through
664 /// the lockset in deterministic order, so this function orders diagnostics
665 /// and outputs them.
666 void emitDiagnostics() {
Benjamin Kramerecafd302012-03-26 14:05:40 +0000667 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000668 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith2e515622012-02-03 04:45:26 +0000669 I != E; ++I) {
670 S.Diag(I->first.first, I->first.second);
671 const OptionalNotes &Notes = I->second;
672 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
673 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
674 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000675 }
676
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000677 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +0000678 PartialDiagnosticAt Warning(Loc,
679 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
680 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000681 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000682 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
683 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
684 }
685
686 void handleDoubleLock(Name LockName, SourceLocation Loc) {
687 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
688 }
689
Richard Smith2e515622012-02-03 04:45:26 +0000690 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
691 SourceLocation LocEndOfScope,
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000692 LockErrorKind LEK){
693 unsigned DiagID = 0;
694 switch (LEK) {
695 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +0000696 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000697 break;
698 case LEK_LockedSomeLoopIterations:
699 DiagID = diag::warn_expecting_lock_held_on_loop;
700 break;
701 case LEK_LockedAtEndOfFunction:
702 DiagID = diag::warn_no_unlock;
703 break;
704 }
Richard Smith2e515622012-02-03 04:45:26 +0000705 if (LocEndOfScope.isInvalid())
706 LocEndOfScope = FunEndLocation;
707
708 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
709 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
710 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000711 }
712
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000713
714 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
715 SourceLocation Loc2) {
Richard Smith2e515622012-02-03 04:45:26 +0000716 PartialDiagnosticAt Warning(
717 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
718 PartialDiagnosticAt Note(
719 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
720 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000721 }
722
723 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
724 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +0000725 assert((POK == POK_VarAccess || POK == POK_VarDereference)
726 && "Only works for variables");
727 unsigned DiagID = POK == POK_VarAccess?
728 diag::warn_variable_requires_any_lock:
729 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +0000730 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
731 << D->getName() << getLockKindFromAccessKind(AK));
732 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000733 }
734
735 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
736 Name LockName, LockKind LK, SourceLocation Loc) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +0000737 unsigned DiagID = 0;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000738 switch (POK) {
739 case POK_VarAccess:
740 DiagID = diag::warn_variable_requires_lock;
741 break;
742 case POK_VarDereference:
743 DiagID = diag::warn_var_deref_requires_lock;
744 break;
745 case POK_FunctionCall:
746 DiagID = diag::warn_fun_requires_lock;
747 break;
748 }
Richard Smith2e515622012-02-03 04:45:26 +0000749 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
750 << D->getName() << LockName << LK);
751 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000752 }
753
754 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +0000755 PartialDiagnosticAt Warning(Loc,
756 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
757 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000758 }
759};
760}
761}
David Blaikie99ba9e32011-12-20 02:48:34 +0000762}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000763
Ted Kremenek610068c2011-01-15 02:58:47 +0000764//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000765// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
766// warnings on a function, method, or block.
767//===----------------------------------------------------------------------===//
768
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000769clang::sema::AnalysisBasedWarnings::Policy::Policy() {
770 enableCheckFallThrough = 1;
771 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000772 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000773}
774
Chandler Carruth5d989942011-07-06 16:21:37 +0000775clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
776 : S(s),
777 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000778 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +0000779 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000780 MaxCFGBlocksPerFunction(0),
781 NumUninitAnalysisFunctions(0),
782 NumUninitAnalysisVariables(0),
783 MaxUninitAnalysisVariablesPerFunction(0),
784 NumUninitAnalysisBlockVisits(0),
785 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +0000786 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000787 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000788 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +0000789 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000790 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
791 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +0000792 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000793
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000794}
795
Ted Kremenek351ba912011-02-23 01:52:04 +0000796static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000797 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +0000798 i = fscope->PossiblyUnreachableDiags.begin(),
799 e = fscope->PossiblyUnreachableDiags.end();
800 i != e; ++i) {
801 const sema::PossiblyUnreachableDiag &D = *i;
802 S.Diag(D.Loc, D.PD);
803 }
804}
805
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000806void clang::sema::
807AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000808 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000809 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000810
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000811 // We avoid doing analysis-based warnings when there are errors for
812 // two reasons:
813 // (1) The CFGs often can't be constructed (if the body is invalid), so
814 // don't bother trying.
815 // (2) The code already has problems; running the analysis just takes more
816 // time.
David Blaikied6471f72011-09-25 23:23:43 +0000817 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +0000818
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000819 // Do not do any analysis for declarations in system headers if we are
820 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000821 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000822 S.SourceMgr.isInSystemHeader(D->getLocation()))
823 return;
824
John McCalle0054f62010-08-25 05:56:39 +0000825 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +0000826 if (cast<DeclContext>(D)->isDependentContext())
827 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000828
Ted Kremenek351ba912011-02-23 01:52:04 +0000829 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
830 // Flush out any possibly unreachable diagnostics.
831 flushDiagnostics(S, fscope);
832 return;
833 }
834
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000835 const Stmt *Body = D->getBody();
836 assert(Body);
837
Jordy Rosed2001872012-04-28 01:58:08 +0000838 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000839
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000840 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
841 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000842 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
843 AC.getCFGBuildOptions().AddEHEdges = false;
844 AC.getCFGBuildOptions().AddInitializers = true;
845 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000846
847 // Force that certain expressions appear as CFGElements in the CFG. This
848 // is used to speed up various analyses.
849 // FIXME: This isn't the right factoring. This is here for initial
850 // prototyping, but we need a way for analyses to say what expressions they
851 // expect to always be CFGElements and then fill in the BuildOptions
852 // appropriately. This is essentially a layering violation.
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000853 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
854 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000855 AC.getCFGBuildOptions().setAllAlwaysAdd();
856 }
857 else {
858 AC.getCFGBuildOptions()
859 .setAlwaysAdd(Stmt::BinaryOperatorClass)
860 .setAlwaysAdd(Stmt::BlockExprClass)
861 .setAlwaysAdd(Stmt::CStyleCastExprClass)
862 .setAlwaysAdd(Stmt::DeclRefExprClass)
863 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
864 .setAlwaysAdd(Stmt::UnaryOperatorClass);
865 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000866
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000867 // Construct the analysis context with the specified CFG build options.
868
Ted Kremenek351ba912011-02-23 01:52:04 +0000869 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +0000870 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000871 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000872
873 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000874 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000875 i = fscope->PossiblyUnreachableDiags.begin(),
876 e = fscope->PossiblyUnreachableDiags.end();
877 i != e; ++i) {
878 if (const Stmt *stmt = i->stmt)
879 AC.registerForcedBlockExpression(stmt);
880 }
881
882 if (AC.getCFG()) {
883 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000884 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000885 i = fscope->PossiblyUnreachableDiags.begin(),
886 e = fscope->PossiblyUnreachableDiags.end();
887 i != e; ++i)
888 {
889 const sema::PossiblyUnreachableDiag &D = *i;
890 bool processed = false;
891 if (const Stmt *stmt = i->stmt) {
892 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +0000893 CFGReverseBlockReachabilityAnalysis *cra =
894 AC.getCFGReachablityAnalysis();
895 // FIXME: We should be able to assert that block is non-null, but
896 // the CFG analysis can skip potentially-evaluated expressions in
897 // edge cases; see test/Sema/vla-2.c.
898 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000899 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000900 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000901 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000902 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000903 }
904 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000905 if (!processed) {
906 // Emit the warning anyway if we cannot map to a basic block.
907 S.Diag(D.Loc, D.PD);
908 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000909 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000910 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000911
912 if (!analyzed)
913 flushDiagnostics(S, fscope);
914 }
915
916
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000917 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +0000918 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000919 const CheckFallThroughDiagnostics &CD =
920 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000921 : (isa<CXXMethodDecl>(D) &&
922 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
923 cast<CXXMethodDecl>(D)->getParent()->isLambda())
924 ? CheckFallThroughDiagnostics::MakeForLambda()
925 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000926 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000927 }
928
929 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +0000930 if (P.enableCheckUnreachable) {
931 // Only check for unreachable code on non-template instantiations.
932 // Different template instantiations can effectively change the control-flow
933 // and it is very difficult to prove that a snippet of code in a template
934 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000935 bool isTemplateInstantiation = false;
936 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
937 isTemplateInstantiation = Function->isTemplateInstantiation();
938 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +0000939 CheckUnreachable(S, AC);
940 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000941
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000942 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +0000943 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000944 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +0000945 SourceLocation FEL = AC.getDecl()->getLocEnd();
946 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000947 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
948 Reporter.emitDiagnostics();
949 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000950
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000951 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +0000952 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +0000953 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +0000954 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000955 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000956 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +0000957 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +0000958 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000959 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +0000960 reporter, stats);
961
962 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
963 ++NumUninitAnalysisFunctions;
964 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
965 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
966 MaxUninitAnalysisVariablesPerFunction =
967 std::max(MaxUninitAnalysisVariablesPerFunction,
968 stats.NumVariablesAnalyzed);
969 MaxUninitAnalysisBlockVisitsPerFunction =
970 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
971 stats.NumBlockVisits);
972 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000973 }
974 }
Chandler Carruth5d989942011-07-06 16:21:37 +0000975
976 // Collect statistics about the CFG if it was built.
977 if (S.CollectStats && AC.isCFGBuilt()) {
978 ++NumFunctionsAnalyzed;
979 if (CFG *cfg = AC.getCFG()) {
980 // If we successfully built a CFG for this context, record some more
981 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000982 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +0000983 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000984 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +0000985 } else {
986 ++NumFunctionsWithBadCFGs;
987 }
988 }
989}
990
991void clang::sema::AnalysisBasedWarnings::PrintStats() const {
992 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
993
994 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
995 unsigned AvgCFGBlocksPerFunction =
996 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
997 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
998 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
999 << " " << NumCFGBlocks << " CFG blocks built.\n"
1000 << " " << AvgCFGBlocksPerFunction
1001 << " average CFG blocks per function.\n"
1002 << " " << MaxCFGBlocksPerFunction
1003 << " max CFG blocks per function.\n";
1004
1005 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1006 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1007 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1008 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1009 llvm::errs() << NumUninitAnalysisFunctions
1010 << " functions analyzed for uninitialiazed variables\n"
1011 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1012 << " " << AvgUninitVariablesPerFunction
1013 << " average variables per function.\n"
1014 << " " << MaxUninitAnalysisVariablesPerFunction
1015 << " max variables per function.\n"
1016 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1017 << " " << AvgUninitBlockVisitsPerFunction
1018 << " average block visits per function.\n"
1019 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1020 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001021}