blob: efb71baddbceb99be716ea04c9d137070a74e473 [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 Carruth9f649462011-04-05 06:48:00 +0000413static bool isSelfInit(ASTContext &Context,
414 const VarDecl *VD, const DeclRefExpr *DR) {
415 if (const Expr *E = VD->getInit()) {
416 ContainsReference CR(Context, DR);
417 CR.Visit(const_cast<Expr*>(E));
418 return CR.doesContainReference();
Ted Kremenek6f417152011-04-04 20:56:00 +0000419 }
420 return false;
421}
422
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000423typedef std::pair<const Expr*, bool> UninitUse;
424
Ted Kremenek610068c2011-01-15 02:58:47 +0000425namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000426struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000427 bool operator()(const UninitUse &a, const UninitUse &b) {
428 SourceLocation aLoc = a.first->getLocStart();
429 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000430 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
431 }
432};
433
Ted Kremenek610068c2011-01-15 02:58:47 +0000434class UninitValsDiagReporter : public UninitVariablesHandler {
435 Sema &S;
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000436 typedef llvm::SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000437 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
438 UsesMap *uses;
439
Ted Kremenek610068c2011-01-15 02:58:47 +0000440public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000441 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
442 ~UninitValsDiagReporter() {
443 flushDiagnostics();
444 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000445
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000446 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
447 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000448 if (!uses)
449 uses = new UsesMap();
450
451 UsesVec *&vec = (*uses)[vd];
452 if (!vec)
453 vec = new UsesVec();
454
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000455 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000456 }
457
458 void flushDiagnostics() {
459 if (!uses)
460 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000461
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000462 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
463 const VarDecl *vd = i->first;
464 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000465
466 bool fixitIssued = false;
467
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000468 // Sort the uses by their SourceLocations. While not strictly
469 // guaranteed to produce them in line/column order, this will provide
470 // a stable ordering.
471 std::sort(vec->begin(), vec->end(), SLocSort());
472
473 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve; ++vi)
474 {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000475 const bool isAlwaysUninit = vi->second;
Ted Kremenekd40066b2011-04-04 23:29:12 +0000476 bool showDefinition = true;
477
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000478 if (const DeclRefExpr *dr = dyn_cast<DeclRefExpr>(vi->first)) {
Ted Kremenekd40066b2011-04-04 23:29:12 +0000479 if (isAlwaysUninit) {
480 if (isSelfInit(S.Context, vd, dr)) {
481 S.Diag(dr->getLocStart(),
482 diag::warn_uninit_self_reference_in_init)
483 << vd->getDeclName() << vd->getLocation() << dr->getSourceRange();
484 showDefinition = false;
485 }
486 else {
487 S.Diag(dr->getLocStart(), diag::warn_uninit_var)
488 << vd->getDeclName() << dr->getSourceRange();
489 }
490 }
491 else {
492 S.Diag(dr->getLocStart(), diag::warn_maybe_uninit_var)
493 << vd->getDeclName() << dr->getSourceRange();
494 }
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000495 }
496 else {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000497 const BlockExpr *be = cast<BlockExpr>(vi->first);
498 S.Diag(be->getLocStart(),
499 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
500 : diag::warn_maybe_uninit_var_captured_by_block)
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000501 << vd->getDeclName();
502 }
Ted Kremenek609e3172011-02-02 23:35:53 +0000503
504 // Report where the variable was declared.
Ted Kremenekd40066b2011-04-04 23:29:12 +0000505 if (showDefinition)
506 S.Diag(vd->getLocStart(), diag::note_uninit_var_def)
507 << vd->getDeclName();
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000508
Ted Kremenek609e3172011-02-02 23:35:53 +0000509 // Only report the fixit once.
510 if (fixitIssued)
511 continue;
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000512
Ted Kremenek609e3172011-02-02 23:35:53 +0000513 fixitIssued = true;
Ted Kremenek5360c922011-04-04 19:43:57 +0000514
515 // Don't issue a fixit if there is already an initializer.
516 if (vd->getInit())
517 continue;
Ted Kremenek609e3172011-02-02 23:35:53 +0000518
519 // Suggest possible initialization (if any).
520 const char *initialization = 0;
521 QualType vdTy = vd->getType().getCanonicalType();
Ted Kremenek09f57b92011-02-05 01:18:18 +0000522
Ted Kremenek609e3172011-02-02 23:35:53 +0000523 if (vdTy->getAs<ObjCObjectPointerType>()) {
524 // Check if 'nil' is defined.
525 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
526 initialization = " = nil";
527 else
528 initialization = " = 0";
529 }
530 else if (vdTy->isRealFloatingType())
531 initialization = " = 0.0";
532 else if (vdTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
533 initialization = " = false";
Ted Kremenek09f57b92011-02-05 01:18:18 +0000534 else if (vdTy->isEnumeralType())
535 continue;
Ted Kremenek609e3172011-02-02 23:35:53 +0000536 else if (vdTy->isScalarType())
Ted Kremenekdcfb3602011-01-21 22:49:49 +0000537 initialization = " = 0";
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000538
Ted Kremenek609e3172011-02-02 23:35:53 +0000539 if (initialization) {
540 SourceLocation loc = S.PP.getLocForEndOfToken(vd->getLocEnd());
541 S.Diag(loc, diag::note_var_fixit_add_initialization)
542 << FixItHint::CreateInsertion(loc, initialization);
543 }
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000544 }
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000545 delete vec;
546 }
547 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000548 }
549};
550}
551
552//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000553// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
554// warnings on a function, method, or block.
555//===----------------------------------------------------------------------===//
556
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000557clang::sema::AnalysisBasedWarnings::Policy::Policy() {
558 enableCheckFallThrough = 1;
559 enableCheckUnreachable = 0;
560}
561
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000562clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
563 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000564 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000565 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
566 Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000567}
568
Ted Kremenek351ba912011-02-23 01:52:04 +0000569static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
570 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
571 i = fscope->PossiblyUnreachableDiags.begin(),
572 e = fscope->PossiblyUnreachableDiags.end();
573 i != e; ++i) {
574 const sema::PossiblyUnreachableDiag &D = *i;
575 S.Diag(D.Loc, D.PD);
576 }
577}
578
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000579void clang::sema::
580AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000581 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000582 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000583
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000584 // We avoid doing analysis-based warnings when there are errors for
585 // two reasons:
586 // (1) The CFGs often can't be constructed (if the body is invalid), so
587 // don't bother trying.
588 // (2) The code already has problems; running the analysis just takes more
589 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000590 Diagnostic &Diags = S.getDiagnostics();
591
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000592 // Do not do any analysis for declarations in system headers if we are
593 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000594 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000595 S.SourceMgr.isInSystemHeader(D->getLocation()))
596 return;
597
John McCalle0054f62010-08-25 05:56:39 +0000598 // For code in dependent contexts, we'll do this at instantiation time.
599 if (cast<DeclContext>(D)->isDependentContext())
600 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000601
Ted Kremenek351ba912011-02-23 01:52:04 +0000602 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
603 // Flush out any possibly unreachable diagnostics.
604 flushDiagnostics(S, fscope);
605 return;
606 }
607
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000608 const Stmt *Body = D->getBody();
609 assert(Body);
610
611 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
612 // explosion for destrutors that can result and the compile time hit.
Chandler Carrutheeef9242011-01-08 06:54:40 +0000613 AnalysisContext AC(D, 0, /*useUnoptimizedCFG=*/false, /*addehedges=*/false,
614 /*addImplicitDtors=*/true, /*addInitializers=*/true);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000615
Ted Kremenek351ba912011-02-23 01:52:04 +0000616 // Emit delayed diagnostics.
617 if (!fscope->PossiblyUnreachableDiags.empty()) {
618 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000619
620 // Register the expressions with the CFGBuilder.
621 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
622 i = fscope->PossiblyUnreachableDiags.begin(),
623 e = fscope->PossiblyUnreachableDiags.end();
624 i != e; ++i) {
625 if (const Stmt *stmt = i->stmt)
626 AC.registerForcedBlockExpression(stmt);
627 }
628
629 if (AC.getCFG()) {
630 analyzed = true;
631 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
632 i = fscope->PossiblyUnreachableDiags.begin(),
633 e = fscope->PossiblyUnreachableDiags.end();
634 i != e; ++i)
635 {
636 const sema::PossiblyUnreachableDiag &D = *i;
637 bool processed = false;
638 if (const Stmt *stmt = i->stmt) {
639 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
640 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000641 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000642 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000643 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000644 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000645 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000646 }
647 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000648 if (!processed) {
649 // Emit the warning anyway if we cannot map to a basic block.
650 S.Diag(D.Loc, D.PD);
651 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000652 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000653 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000654
655 if (!analyzed)
656 flushDiagnostics(S, fscope);
657 }
658
659
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000660 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000661 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000662 const CheckFallThroughDiagnostics &CD =
663 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000664 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000665 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000666 }
667
668 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000669 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000670 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +0000671
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000672 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +0000673 != Diagnostic::Ignored ||
674 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000675 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000676 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000677 UninitValsDiagReporter reporter(S);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000678 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
679 reporter);
Ted Kremenek610068c2011-01-15 02:58:47 +0000680 }
681 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000682}