blob: e482172ca3eb94d488a638f913a48ea78ffb1547 [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"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000020#include "clang/Lex/Preprocessor.h"
John McCall7cd088e2010-08-24 07:21:54 +000021#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000023#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000028#include "clang/Analysis/AnalysisContext.h"
29#include "clang/Analysis/CFG.h"
30#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000031#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
32#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000033#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000034#include "llvm/ADT/BitVector.h"
35#include "llvm/Support/Casting.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000036
37using namespace clang;
38
39//===----------------------------------------------------------------------===//
40// Unreachable code analysis.
41//===----------------------------------------------------------------------===//
42
43namespace {
44 class UnreachableCodeHandler : public reachable_code::Callback {
45 Sema &S;
46 public:
47 UnreachableCodeHandler(Sema &s) : S(s) {}
48
49 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
50 S.Diag(L, diag::warn_unreachable) << R1 << R2;
51 }
52 };
53}
54
55/// CheckUnreachable - Check for unreachable code.
56static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
57 UnreachableCodeHandler UC(S);
58 reachable_code::FindUnreachableCode(AC, UC);
59}
60
61//===----------------------------------------------------------------------===//
62// Check for missing return value.
63//===----------------------------------------------------------------------===//
64
John McCall16565aa2010-05-16 09:34:11 +000065enum ControlFlowKind {
66 UnknownFallThrough,
67 NeverFallThrough,
68 MaybeFallThrough,
69 AlwaysFallThrough,
70 NeverFallThroughOrReturn
71};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000072
73/// CheckFallThrough - Check that we don't fall off the end of a
74/// Statement that should return a value.
75///
76/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
77/// MaybeFallThrough iff we might or might not fall off the end,
78/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
79/// return. We assume NeverFallThrough iff we never fall off the end of the
80/// statement but we may return. We assume that functions not marked noreturn
81/// will return.
82static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
83 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000084 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000085
86 // The CFG leaves in dead things, and we don't want the dead code paths to
87 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000088 llvm::BitVector live(cfg->getNumBlockIDs());
89 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
90 live);
91
92 bool AddEHEdges = AC.getAddEHEdges();
93 if (!AddEHEdges && count != cfg->getNumBlockIDs())
94 // When there are things remaining dead, and we didn't add EH edges
95 // from CallExprs to the catch clauses, we have to go back and
96 // mark them as live.
97 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
98 CFGBlock &b = **I;
99 if (!live[b.getBlockID()]) {
100 if (b.pred_begin() == b.pred_end()) {
101 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
102 // When not adding EH edges from calls, catch clauses
103 // can otherwise seem dead. Avoid noting them as dead.
104 count += reachable_code::ScanReachableFromBlock(b, live);
105 continue;
106 }
107 }
108 }
109
110 // Now we know what is live, we check the live precessors of the exit block
111 // and look for fall through paths, being careful to ignore normal returns,
112 // and exceptional paths.
113 bool HasLiveReturn = false;
114 bool HasFakeEdge = false;
115 bool HasPlainEdge = false;
116 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000117
118 // Ignore default cases that aren't likely to be reachable because all
119 // enums in a switch(X) have explicit case statements.
120 CFGBlock::FilterOptions FO;
121 FO.IgnoreDefaultsWithCoveredEnums = 1;
122
123 for (CFGBlock::filtered_pred_iterator
124 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
125 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000126 if (!live[B.getBlockID()])
127 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000128
129 // Destructors can appear after the 'return' in the CFG. This is
130 // normal. We need to look pass the destructors for the return
131 // statement (if it exists).
132 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000133 bool hasNoReturnDtor = false;
134
Ted Kremenek5811f592011-01-26 04:49:52 +0000135 for ( ; ri != re ; ++ri) {
136 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000137
138 // FIXME: The right solution is to just sever the edges in the
139 // CFG itself.
140 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
Ted Kremenekc5aff442011-03-03 01:21:32 +0000141 if (iDtor->isNoReturn(AC.getASTContext())) {
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000142 hasNoReturnDtor = true;
143 HasFakeEdge = true;
144 break;
145 }
146
Ted Kremenek5811f592011-01-26 04:49:52 +0000147 if (isa<CFGStmt>(CE))
148 break;
149 }
150
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000151 if (hasNoReturnDtor)
152 continue;
153
Ted Kremenek5811f592011-01-26 04:49:52 +0000154 // No more CFGElements in the block?
155 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000156 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
157 HasAbnormalEdge = true;
158 continue;
159 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000160 // A labeled empty statement, or the entry block...
161 HasPlainEdge = true;
162 continue;
163 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000164
Ted Kremenek5811f592011-01-26 04:49:52 +0000165 CFGStmt CS = cast<CFGStmt>(*ri);
Zhongxing Xub36cd3e2010-09-16 01:25:47 +0000166 Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000167 if (isa<ReturnStmt>(S)) {
168 HasLiveReturn = true;
169 continue;
170 }
171 if (isa<ObjCAtThrowStmt>(S)) {
172 HasFakeEdge = true;
173 continue;
174 }
175 if (isa<CXXThrowExpr>(S)) {
176 HasFakeEdge = true;
177 continue;
178 }
179 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
180 if (AS->isMSAsm()) {
181 HasFakeEdge = true;
182 HasLiveReturn = true;
183 continue;
184 }
185 }
186 if (isa<CXXTryStmt>(S)) {
187 HasAbnormalEdge = true;
188 continue;
189 }
190
191 bool NoReturnEdge = false;
192 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000193 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
194 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000195 HasAbnormalEdge = true;
196 continue;
197 }
198 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Rafael Espindola264ba482010-03-30 20:24:48 +0000199 if (getFunctionExtInfo(CEE->getType()).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000200 NoReturnEdge = true;
201 HasFakeEdge = true;
202 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
203 ValueDecl *VD = DRE->getDecl();
204 if (VD->hasAttr<NoReturnAttr>()) {
205 NoReturnEdge = true;
206 HasFakeEdge = true;
207 }
208 }
209 }
210 // FIXME: Add noreturn message sends.
211 if (NoReturnEdge == false)
212 HasPlainEdge = true;
213 }
214 if (!HasPlainEdge) {
215 if (HasLiveReturn)
216 return NeverFallThrough;
217 return NeverFallThroughOrReturn;
218 }
219 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
220 return MaybeFallThrough;
221 // This says AlwaysFallThrough for calls to functions that are not marked
222 // noreturn, that don't return. If people would like this warning to be more
223 // accurate, such functions should be marked as noreturn.
224 return AlwaysFallThrough;
225}
226
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000227namespace {
228
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000229struct CheckFallThroughDiagnostics {
230 unsigned diag_MaybeFallThrough_HasNoReturn;
231 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
232 unsigned diag_AlwaysFallThrough_HasNoReturn;
233 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
234 unsigned diag_NeverFallThroughOrReturn;
235 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000236 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000237
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000238 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000239 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000240 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000241 D.diag_MaybeFallThrough_HasNoReturn =
242 diag::warn_falloff_noreturn_function;
243 D.diag_MaybeFallThrough_ReturnsNonVoid =
244 diag::warn_maybe_falloff_nonvoid_function;
245 D.diag_AlwaysFallThrough_HasNoReturn =
246 diag::warn_falloff_noreturn_function;
247 D.diag_AlwaysFallThrough_ReturnsNonVoid =
248 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000249
250 // Don't suggest that virtual functions be marked "noreturn", since they
251 // might be overridden by non-noreturn functions.
252 bool isVirtualMethod = false;
253 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
254 isVirtualMethod = Method->isVirtual();
255
256 if (!isVirtualMethod)
257 D.diag_NeverFallThroughOrReturn =
258 diag::warn_suggest_noreturn_function;
259 else
260 D.diag_NeverFallThroughOrReturn = 0;
261
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000262 D.funMode = true;
263 return D;
264 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000265
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000266 static CheckFallThroughDiagnostics MakeForBlock() {
267 CheckFallThroughDiagnostics D;
268 D.diag_MaybeFallThrough_HasNoReturn =
269 diag::err_noreturn_block_has_return_expr;
270 D.diag_MaybeFallThrough_ReturnsNonVoid =
271 diag::err_maybe_falloff_nonvoid_block;
272 D.diag_AlwaysFallThrough_HasNoReturn =
273 diag::err_noreturn_block_has_return_expr;
274 D.diag_AlwaysFallThrough_ReturnsNonVoid =
275 diag::err_falloff_nonvoid_block;
276 D.diag_NeverFallThroughOrReturn =
277 diag::warn_suggest_noreturn_block;
278 D.funMode = false;
279 return D;
280 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000281
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000282 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
283 bool HasNoReturn) const {
284 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000285 return (ReturnsVoid ||
286 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
287 FuncLoc) == Diagnostic::Ignored)
288 && (!HasNoReturn ||
289 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
290 FuncLoc) == Diagnostic::Ignored)
291 && (!ReturnsVoid ||
292 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
293 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000294 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000295
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000296 // For blocks.
297 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000298 && (!ReturnsVoid ||
299 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
300 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000301 }
302};
303
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000304}
305
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000306/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
307/// function that should return a value. Check that we don't fall off the end
308/// of a noreturn function. We assume that functions and blocks not marked
309/// noreturn will return.
310static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000311 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000312 const CheckFallThroughDiagnostics& CD,
313 AnalysisContext &AC) {
314
315 bool ReturnsVoid = false;
316 bool HasNoReturn = false;
317
318 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
319 ReturnsVoid = FD->getResultType()->isVoidType();
320 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000321 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000322 }
323 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
324 ReturnsVoid = MD->getResultType()->isVoidType();
325 HasNoReturn = MD->hasAttr<NoReturnAttr>();
326 }
327 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000328 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000329 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000330 BlockTy->getPointeeType()->getAs<FunctionType>()) {
331 if (FT->getResultType()->isVoidType())
332 ReturnsVoid = true;
333 if (FT->getNoReturnAttr())
334 HasNoReturn = true;
335 }
336 }
337
338 Diagnostic &Diags = S.getDiagnostics();
339
340 // Short circuit for compilation speed.
341 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
342 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000343
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000344 // FIXME: Function try block
345 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
346 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000347 case UnknownFallThrough:
348 break;
349
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000350 case MaybeFallThrough:
351 if (HasNoReturn)
352 S.Diag(Compound->getRBracLoc(),
353 CD.diag_MaybeFallThrough_HasNoReturn);
354 else if (!ReturnsVoid)
355 S.Diag(Compound->getRBracLoc(),
356 CD.diag_MaybeFallThrough_ReturnsNonVoid);
357 break;
358 case AlwaysFallThrough:
359 if (HasNoReturn)
360 S.Diag(Compound->getRBracLoc(),
361 CD.diag_AlwaysFallThrough_HasNoReturn);
362 else if (!ReturnsVoid)
363 S.Diag(Compound->getRBracLoc(),
364 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
365 break;
366 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000367 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000368 S.Diag(Compound->getLBracLoc(),
369 CD.diag_NeverFallThroughOrReturn);
370 break;
371 case NeverFallThrough:
372 break;
373 }
374 }
375}
376
377//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000378// -Wuninitialized
379//===----------------------------------------------------------------------===//
380
Ted Kremenek6f417152011-04-04 20:56:00 +0000381namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000382/// ContainsReference - A visitor class to search for references to
383/// a particular declaration (the needle) within any evaluated component of an
384/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000385class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000386 bool FoundReference;
387 const DeclRefExpr *Needle;
388
Ted Kremenek6f417152011-04-04 20:56:00 +0000389public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000390 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
391 : EvaluatedExprVisitor<ContainsReference>(Context),
392 FoundReference(false), Needle(Needle) {}
393
394 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000395 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000396 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000397 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000398
399 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000400 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000401
402 void VisitDeclRefExpr(DeclRefExpr *E) {
403 if (E == Needle)
404 FoundReference = true;
405 else
406 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000407 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000408
409 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000410};
411}
412
Chandler Carruth262d50e2011-04-05 18:27:05 +0000413/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
414/// uninitialized variable. This manages the different forms of diagnostic
415/// emitted for particular types of uses. Returns true if the use was diagnosed
416/// as a warning. If a pariticular use is one we omit warnings for, returns
417/// false.
418static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Chandler Carruth64fb9592011-04-05 18:18:08 +0000419 const Expr *E, bool isAlwaysUninit) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000420 bool isSelfInit = false;
421
422 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
423 if (isAlwaysUninit) {
424 // Inspect the initializer of the variable declaration which is
425 // being referenced prior to its initialization. We emit
426 // specialized diagnostics for self-initialization, and we
427 // specifically avoid warning about self references which take the
428 // form of:
429 //
430 // int x = x;
431 //
432 // This is used to indicate to GCC that 'x' is intentionally left
433 // uninitialized. Proven code paths which access 'x' in
434 // an uninitialized state after this will still warn.
435 //
436 // TODO: Should we suppress maybe-uninitialized warnings for
437 // variables initialized in this way?
438 if (const Expr *Initializer = VD->getInit()) {
439 if (DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000440 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000441
442 ContainsReference CR(S.Context, DRE);
443 CR.Visit(const_cast<Expr*>(Initializer));
444 isSelfInit = CR.doesContainReference();
445 }
446 if (isSelfInit) {
447 S.Diag(DRE->getLocStart(),
448 diag::warn_uninit_self_reference_in_init)
449 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
450 } else {
451 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
452 << VD->getDeclName() << DRE->getSourceRange();
453 }
454 } else {
455 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
456 << VD->getDeclName() << DRE->getSourceRange();
457 }
458 } else {
459 const BlockExpr *BE = cast<BlockExpr>(E);
460 S.Diag(BE->getLocStart(),
461 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
462 : diag::warn_maybe_uninit_var_captured_by_block)
463 << VD->getDeclName();
464 }
465
466 // Report where the variable was declared when the use wasn't within
467 // the initializer of that declaration.
468 if (!isSelfInit)
469 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
470 << VD->getDeclName();
471
Chandler Carruth262d50e2011-04-05 18:27:05 +0000472 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000473}
474
Chandler Carruth262d50e2011-04-05 18:27:05 +0000475static void SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000476 // Don't issue a fixit if there is already an initializer.
477 if (VD->getInit())
478 return;
479
480 // Suggest possible initialization (if any).
481 const char *initialization = 0;
482 QualType VariableTy = VD->getType().getCanonicalType();
483
484 if (VariableTy->getAs<ObjCObjectPointerType>()) {
485 // Check if 'nil' is defined.
486 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
487 initialization = " = nil";
488 else
489 initialization = " = 0";
490 }
491 else if (VariableTy->isRealFloatingType())
492 initialization = " = 0.0";
493 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
494 initialization = " = false";
495 else if (VariableTy->isEnumeralType())
496 return;
497 else if (VariableTy->isScalarType())
498 initialization = " = 0";
499
500 if (initialization) {
501 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
502 S.Diag(loc, diag::note_var_fixit_add_initialization)
503 << FixItHint::CreateInsertion(loc, initialization);
504 }
505}
506
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000507typedef std::pair<const Expr*, bool> UninitUse;
508
Ted Kremenek610068c2011-01-15 02:58:47 +0000509namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000510struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000511 bool operator()(const UninitUse &a, const UninitUse &b) {
512 SourceLocation aLoc = a.first->getLocStart();
513 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000514 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
515 }
516};
517
Ted Kremenek610068c2011-01-15 02:58:47 +0000518class UninitValsDiagReporter : public UninitVariablesHandler {
519 Sema &S;
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000520 typedef llvm::SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000521 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
522 UsesMap *uses;
523
Ted Kremenek610068c2011-01-15 02:58:47 +0000524public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000525 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
526 ~UninitValsDiagReporter() {
527 flushDiagnostics();
528 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000529
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000530 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
531 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000532 if (!uses)
533 uses = new UsesMap();
534
535 UsesVec *&vec = (*uses)[vd];
536 if (!vec)
537 vec = new UsesVec();
538
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000539 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000540 }
541
542 void flushDiagnostics() {
543 if (!uses)
544 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000545
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000546 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
547 const VarDecl *vd = i->first;
548 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000549
550 bool fixitIssued = false;
551
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000552 // Sort the uses by their SourceLocations. While not strictly
553 // guaranteed to produce them in line/column order, this will provide
554 // a stable ordering.
555 std::sort(vec->begin(), vec->end(), SLocSort());
556
Chandler Carruth64fb9592011-04-05 18:18:08 +0000557 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
558 ++vi) {
Chandler Carruth262d50e2011-04-05 18:27:05 +0000559 if (!DiagnoseUninitializedUse(S, vd, vi->first,
560 /*isAlwaysUninit=*/vi->second))
561 continue;
562
563 // Suggest a fixit hint the first time we diagnose a use of a variable.
564 if (!fixitIssued) {
565 SuggestInitializationFixit(S, vd);
566 fixitIssued = true;
567 }
Chandler Carruth64fb9592011-04-05 18:18:08 +0000568 }
Ted Kremenekd40066b2011-04-04 23:29:12 +0000569
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000570 delete vec;
571 }
572 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000573 }
574};
575}
576
577//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000578// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
579// warnings on a function, method, or block.
580//===----------------------------------------------------------------------===//
581
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000582clang::sema::AnalysisBasedWarnings::Policy::Policy() {
583 enableCheckFallThrough = 1;
584 enableCheckUnreachable = 0;
585}
586
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000587clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
588 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000589 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000590 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
591 Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000592}
593
Ted Kremenek351ba912011-02-23 01:52:04 +0000594static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
595 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
596 i = fscope->PossiblyUnreachableDiags.begin(),
597 e = fscope->PossiblyUnreachableDiags.end();
598 i != e; ++i) {
599 const sema::PossiblyUnreachableDiag &D = *i;
600 S.Diag(D.Loc, D.PD);
601 }
602}
603
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000604void clang::sema::
605AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000606 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000607 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000608
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000609 // We avoid doing analysis-based warnings when there are errors for
610 // two reasons:
611 // (1) The CFGs often can't be constructed (if the body is invalid), so
612 // don't bother trying.
613 // (2) The code already has problems; running the analysis just takes more
614 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000615 Diagnostic &Diags = S.getDiagnostics();
616
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000617 // Do not do any analysis for declarations in system headers if we are
618 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000619 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000620 S.SourceMgr.isInSystemHeader(D->getLocation()))
621 return;
622
John McCalle0054f62010-08-25 05:56:39 +0000623 // For code in dependent contexts, we'll do this at instantiation time.
624 if (cast<DeclContext>(D)->isDependentContext())
625 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000626
Ted Kremenek351ba912011-02-23 01:52:04 +0000627 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
628 // Flush out any possibly unreachable diagnostics.
629 flushDiagnostics(S, fscope);
630 return;
631 }
632
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000633 const Stmt *Body = D->getBody();
634 assert(Body);
635
636 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
637 // explosion for destrutors that can result and the compile time hit.
Chandler Carrutheeef9242011-01-08 06:54:40 +0000638 AnalysisContext AC(D, 0, /*useUnoptimizedCFG=*/false, /*addehedges=*/false,
639 /*addImplicitDtors=*/true, /*addInitializers=*/true);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000640
Ted Kremenek351ba912011-02-23 01:52:04 +0000641 // Emit delayed diagnostics.
642 if (!fscope->PossiblyUnreachableDiags.empty()) {
643 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000644
645 // Register the expressions with the CFGBuilder.
646 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
647 i = fscope->PossiblyUnreachableDiags.begin(),
648 e = fscope->PossiblyUnreachableDiags.end();
649 i != e; ++i) {
650 if (const Stmt *stmt = i->stmt)
651 AC.registerForcedBlockExpression(stmt);
652 }
653
654 if (AC.getCFG()) {
655 analyzed = true;
656 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
657 i = fscope->PossiblyUnreachableDiags.begin(),
658 e = fscope->PossiblyUnreachableDiags.end();
659 i != e; ++i)
660 {
661 const sema::PossiblyUnreachableDiag &D = *i;
662 bool processed = false;
663 if (const Stmt *stmt = i->stmt) {
664 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
665 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000666 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000667 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000668 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000669 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000670 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000671 }
672 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000673 if (!processed) {
674 // Emit the warning anyway if we cannot map to a basic block.
675 S.Diag(D.Loc, D.PD);
676 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000677 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000678 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000679
680 if (!analyzed)
681 flushDiagnostics(S, fscope);
682 }
683
684
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000685 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000686 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000687 const CheckFallThroughDiagnostics &CD =
688 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000689 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000690 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000691 }
692
693 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000694 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000695 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +0000696
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000697 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +0000698 != Diagnostic::Ignored ||
699 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000700 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000701 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000702 UninitValsDiagReporter reporter(S);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000703 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
704 reporter);
Ted Kremenek610068c2011-01-15 02:58:47 +0000705 }
706 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000707}