blob: 775681eebe96cc4d58e1306489454ded757efc26 [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/Sema.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000018#include "clang/Basic/SourceManager.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000020#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000021#include "clang/AST/ExprObjC.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/Analysis/AnalysisContext.h"
26#include "clang/Analysis/CFG.h"
27#include "clang/Analysis/Analyses/ReachableCode.h"
28#include "llvm/ADT/BitVector.h"
29#include "llvm/Support/Casting.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000030
31using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// Unreachable code analysis.
35//===----------------------------------------------------------------------===//
36
37namespace {
38 class UnreachableCodeHandler : public reachable_code::Callback {
39 Sema &S;
40 public:
41 UnreachableCodeHandler(Sema &s) : S(s) {}
42
43 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
44 S.Diag(L, diag::warn_unreachable) << R1 << R2;
45 }
46 };
47}
48
49/// CheckUnreachable - Check for unreachable code.
50static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
51 UnreachableCodeHandler UC(S);
52 reachable_code::FindUnreachableCode(AC, UC);
53}
54
55//===----------------------------------------------------------------------===//
56// Check for missing return value.
57//===----------------------------------------------------------------------===//
58
John McCall16565aa2010-05-16 09:34:11 +000059enum ControlFlowKind {
60 UnknownFallThrough,
61 NeverFallThrough,
62 MaybeFallThrough,
63 AlwaysFallThrough,
64 NeverFallThroughOrReturn
65};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000066
67/// CheckFallThrough - Check that we don't fall off the end of a
68/// Statement that should return a value.
69///
70/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
71/// MaybeFallThrough iff we might or might not fall off the end,
72/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
73/// return. We assume NeverFallThrough iff we never fall off the end of the
74/// statement but we may return. We assume that functions not marked noreturn
75/// will return.
76static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
77 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000078 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000079
80 // The CFG leaves in dead things, and we don't want the dead code paths to
81 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000082 llvm::BitVector live(cfg->getNumBlockIDs());
83 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
84 live);
85
86 bool AddEHEdges = AC.getAddEHEdges();
87 if (!AddEHEdges && count != cfg->getNumBlockIDs())
88 // When there are things remaining dead, and we didn't add EH edges
89 // from CallExprs to the catch clauses, we have to go back and
90 // mark them as live.
91 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
92 CFGBlock &b = **I;
93 if (!live[b.getBlockID()]) {
94 if (b.pred_begin() == b.pred_end()) {
95 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
96 // When not adding EH edges from calls, catch clauses
97 // can otherwise seem dead. Avoid noting them as dead.
98 count += reachable_code::ScanReachableFromBlock(b, live);
99 continue;
100 }
101 }
102 }
103
104 // Now we know what is live, we check the live precessors of the exit block
105 // and look for fall through paths, being careful to ignore normal returns,
106 // and exceptional paths.
107 bool HasLiveReturn = false;
108 bool HasFakeEdge = false;
109 bool HasPlainEdge = false;
110 bool HasAbnormalEdge = false;
111 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
112 E = cfg->getExit().pred_end();
113 I != E;
114 ++I) {
115 CFGBlock& B = **I;
116 if (!live[B.getBlockID()])
117 continue;
118 if (B.size() == 0) {
119 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
120 HasAbnormalEdge = true;
121 continue;
122 }
123
124 // A labeled empty statement, or the entry block...
125 HasPlainEdge = true;
126 continue;
127 }
128 Stmt *S = B[B.size()-1];
129 if (isa<ReturnStmt>(S)) {
130 HasLiveReturn = true;
131 continue;
132 }
133 if (isa<ObjCAtThrowStmt>(S)) {
134 HasFakeEdge = true;
135 continue;
136 }
137 if (isa<CXXThrowExpr>(S)) {
138 HasFakeEdge = true;
139 continue;
140 }
141 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
142 if (AS->isMSAsm()) {
143 HasFakeEdge = true;
144 HasLiveReturn = true;
145 continue;
146 }
147 }
148 if (isa<CXXTryStmt>(S)) {
149 HasAbnormalEdge = true;
150 continue;
151 }
152
153 bool NoReturnEdge = false;
154 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000155 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
156 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000157 HasAbnormalEdge = true;
158 continue;
159 }
160 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Rafael Espindola264ba482010-03-30 20:24:48 +0000161 if (getFunctionExtInfo(CEE->getType()).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000162 NoReturnEdge = true;
163 HasFakeEdge = true;
164 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
165 ValueDecl *VD = DRE->getDecl();
166 if (VD->hasAttr<NoReturnAttr>()) {
167 NoReturnEdge = true;
168 HasFakeEdge = true;
169 }
170 }
171 }
Chandler Carruth00e9cbb2010-05-17 23:51:52 +0000172 // FIXME: Remove this hack once temporaries and their destructors are
173 // modeled correctly by the CFG.
174 if (CXXExprWithTemporaries *E = dyn_cast<CXXExprWithTemporaries>(S)) {
175 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) {
176 const FunctionDecl *FD = E->getTemporary(I)->getDestructor();
177 if (FD->hasAttr<NoReturnAttr>() ||
178 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) {
179 NoReturnEdge = true;
180 HasFakeEdge = true;
181 break;
182 }
183 }
184 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000185 // FIXME: Add noreturn message sends.
186 if (NoReturnEdge == false)
187 HasPlainEdge = true;
188 }
189 if (!HasPlainEdge) {
190 if (HasLiveReturn)
191 return NeverFallThrough;
192 return NeverFallThroughOrReturn;
193 }
194 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
195 return MaybeFallThrough;
196 // This says AlwaysFallThrough for calls to functions that are not marked
197 // noreturn, that don't return. If people would like this warning to be more
198 // accurate, such functions should be marked as noreturn.
199 return AlwaysFallThrough;
200}
201
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000202namespace {
203
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000204struct CheckFallThroughDiagnostics {
205 unsigned diag_MaybeFallThrough_HasNoReturn;
206 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
207 unsigned diag_AlwaysFallThrough_HasNoReturn;
208 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
209 unsigned diag_NeverFallThroughOrReturn;
210 bool funMode;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000211
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000212 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000213 CheckFallThroughDiagnostics D;
214 D.diag_MaybeFallThrough_HasNoReturn =
215 diag::warn_falloff_noreturn_function;
216 D.diag_MaybeFallThrough_ReturnsNonVoid =
217 diag::warn_maybe_falloff_nonvoid_function;
218 D.diag_AlwaysFallThrough_HasNoReturn =
219 diag::warn_falloff_noreturn_function;
220 D.diag_AlwaysFallThrough_ReturnsNonVoid =
221 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000222
223 // Don't suggest that virtual functions be marked "noreturn", since they
224 // might be overridden by non-noreturn functions.
225 bool isVirtualMethod = false;
226 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
227 isVirtualMethod = Method->isVirtual();
228
229 if (!isVirtualMethod)
230 D.diag_NeverFallThroughOrReturn =
231 diag::warn_suggest_noreturn_function;
232 else
233 D.diag_NeverFallThroughOrReturn = 0;
234
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000235 D.funMode = true;
236 return D;
237 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000238
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000239 static CheckFallThroughDiagnostics MakeForBlock() {
240 CheckFallThroughDiagnostics D;
241 D.diag_MaybeFallThrough_HasNoReturn =
242 diag::err_noreturn_block_has_return_expr;
243 D.diag_MaybeFallThrough_ReturnsNonVoid =
244 diag::err_maybe_falloff_nonvoid_block;
245 D.diag_AlwaysFallThrough_HasNoReturn =
246 diag::err_noreturn_block_has_return_expr;
247 D.diag_AlwaysFallThrough_ReturnsNonVoid =
248 diag::err_falloff_nonvoid_block;
249 D.diag_NeverFallThroughOrReturn =
250 diag::warn_suggest_noreturn_block;
251 D.funMode = false;
252 return D;
253 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000254
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000255 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
256 bool HasNoReturn) const {
257 if (funMode) {
258 return (D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
259 == Diagnostic::Ignored || ReturnsVoid)
260 && (D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
261 == Diagnostic::Ignored || !HasNoReturn)
262 && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
263 == Diagnostic::Ignored || !ReturnsVoid);
264 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000265
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000266 // For blocks.
267 return ReturnsVoid && !HasNoReturn
268 && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
269 == Diagnostic::Ignored || !ReturnsVoid);
270 }
271};
272
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000273}
274
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000275/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
276/// function that should return a value. Check that we don't fall off the end
277/// of a noreturn function. We assume that functions and blocks not marked
278/// noreturn will return.
279static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
280 QualType BlockTy,
281 const CheckFallThroughDiagnostics& CD,
282 AnalysisContext &AC) {
283
284 bool ReturnsVoid = false;
285 bool HasNoReturn = false;
286
287 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
288 ReturnsVoid = FD->getResultType()->isVoidType();
289 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000290 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000291 }
292 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
293 ReturnsVoid = MD->getResultType()->isVoidType();
294 HasNoReturn = MD->hasAttr<NoReturnAttr>();
295 }
296 else if (isa<BlockDecl>(D)) {
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000297 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000298 BlockTy->getPointeeType()->getAs<FunctionType>()) {
299 if (FT->getResultType()->isVoidType())
300 ReturnsVoid = true;
301 if (FT->getNoReturnAttr())
302 HasNoReturn = true;
303 }
304 }
305
306 Diagnostic &Diags = S.getDiagnostics();
307
308 // Short circuit for compilation speed.
309 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
310 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000311
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000312 // FIXME: Function try block
313 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
314 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000315 case UnknownFallThrough:
316 break;
317
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000318 case MaybeFallThrough:
319 if (HasNoReturn)
320 S.Diag(Compound->getRBracLoc(),
321 CD.diag_MaybeFallThrough_HasNoReturn);
322 else if (!ReturnsVoid)
323 S.Diag(Compound->getRBracLoc(),
324 CD.diag_MaybeFallThrough_ReturnsNonVoid);
325 break;
326 case AlwaysFallThrough:
327 if (HasNoReturn)
328 S.Diag(Compound->getRBracLoc(),
329 CD.diag_AlwaysFallThrough_HasNoReturn);
330 else if (!ReturnsVoid)
331 S.Diag(Compound->getRBracLoc(),
332 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
333 break;
334 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000335 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000336 S.Diag(Compound->getLBracLoc(),
337 CD.diag_NeverFallThroughOrReturn);
338 break;
339 case NeverFallThrough:
340 break;
341 }
342 }
343}
344
345//===----------------------------------------------------------------------===//
346// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
347// warnings on a function, method, or block.
348//===----------------------------------------------------------------------===//
349
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000350clang::sema::AnalysisBasedWarnings::Policy::Policy() {
351 enableCheckFallThrough = 1;
352 enableCheckUnreachable = 0;
353}
354
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000355clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
356 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000357 DefaultPolicy.enableCheckUnreachable = (unsigned)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000358 (D.getDiagnosticLevel(diag::warn_unreachable) != Diagnostic::Ignored);
359}
360
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000361void clang::sema::
362AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000363 const Decl *D, QualType BlockTy) {
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000364
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000365 assert(BlockTy.isNull() || isa<BlockDecl>(D));
Ted Kremenekd068aab2010-03-20 21:11:09 +0000366
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000367 // We avoid doing analysis-based warnings when there are errors for
368 // two reasons:
369 // (1) The CFGs often can't be constructed (if the body is invalid), so
370 // don't bother trying.
371 // (2) The code already has problems; running the analysis just takes more
372 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000373 Diagnostic &Diags = S.getDiagnostics();
374
375 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000376 return;
377
378 // Do not do any analysis for declarations in system headers if we are
379 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000380 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000381 S.SourceMgr.isInSystemHeader(D->getLocation()))
382 return;
383
John McCalle0054f62010-08-25 05:56:39 +0000384 // For code in dependent contexts, we'll do this at instantiation time.
385 if (cast<DeclContext>(D)->isDependentContext())
386 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000387
388 const Stmt *Body = D->getBody();
389 assert(Body);
390
391 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
392 // explosion for destrutors that can result and the compile time hit.
Zhongxing Xu7a420542010-07-19 13:16:50 +0000393 AnalysisContext AC(D, 0, false);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000394
395 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000396 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000397 const CheckFallThroughDiagnostics &CD =
398 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000399 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000400 CheckFallThroughForBody(S, D, Body, BlockTy, CD, AC);
401 }
402
403 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000404 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000405 CheckUnreachable(S, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000406}
John McCalle0054f62010-08-25 05:56:39 +0000407
408void clang::sema::
409AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
410 const BlockExpr *E) {
411 return IssueWarnings(P, E->getBlockDecl(), E->getType());
412}
413
414void clang::sema::
415AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
416 const ObjCMethodDecl *D) {
417 return IssueWarnings(P, D, QualType());
418}
419
420void clang::sema::
421AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
422 const FunctionDecl *D) {
423 return IssueWarnings(P, D, QualType());
424}