blob: df73fc6da3a74dd1c771239c94370a0c4955e5be [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
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000413typedef std::pair<const Expr*, bool> UninitUse;
414
Ted Kremenek610068c2011-01-15 02:58:47 +0000415namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000416struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000417 bool operator()(const UninitUse &a, const UninitUse &b) {
418 SourceLocation aLoc = a.first->getLocStart();
419 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000420 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
421 }
422};
423
Ted Kremenek610068c2011-01-15 02:58:47 +0000424class UninitValsDiagReporter : public UninitVariablesHandler {
425 Sema &S;
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000426 typedef llvm::SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000427 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
428 UsesMap *uses;
429
Ted Kremenek610068c2011-01-15 02:58:47 +0000430public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000431 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
432 ~UninitValsDiagReporter() {
433 flushDiagnostics();
434 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000435
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000436 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
437 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000438 if (!uses)
439 uses = new UsesMap();
440
441 UsesVec *&vec = (*uses)[vd];
442 if (!vec)
443 vec = new UsesVec();
444
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000445 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000446 }
447
448 void flushDiagnostics() {
449 if (!uses)
450 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000451
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000452 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
453 const VarDecl *vd = i->first;
454 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000455
456 bool fixitIssued = false;
457
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000458 // Sort the uses by their SourceLocations. While not strictly
459 // guaranteed to produce them in line/column order, this will provide
460 // a stable ordering.
461 std::sort(vec->begin(), vec->end(), SLocSort());
462
463 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve; ++vi)
464 {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000465 const bool isAlwaysUninit = vi->second;
Chandler Carruthb414c4f2011-04-05 17:41:31 +0000466 bool isSelfInit = false;
Ted Kremenekd40066b2011-04-04 23:29:12 +0000467
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000468 if (const DeclRefExpr *dr = dyn_cast<DeclRefExpr>(vi->first)) {
Ted Kremenekd40066b2011-04-04 23:29:12 +0000469 if (isAlwaysUninit) {
Chandler Carruthb414c4f2011-04-05 17:41:31 +0000470 // Inspect the initializer of the variable declaration which is
471 // being referenced prior to its initialization. We emit
472 // specialized diagnostics for self-initialization, and we
473 // specifically avoid warning about self references which take the
474 // form of:
475 //
476 // int x = x;
477 //
478 // This is used to indicate to GCC that 'x' is intentionally left
479 // uninitialized. Proven code paths which access 'x' in
480 // an uninitialized state after this will still warn.
481 //
482 // TODO: Should we suppress maybe-uninitialized warnings for
483 // variables initialized in this way?
484 if (const Expr *E = vd->getInit()) {
485 if (dr == E->IgnoreParenImpCasts())
486 continue;
487
488 ContainsReference CR(S.Context, dr);
489 CR.Visit(const_cast<Expr*>(E));
490 isSelfInit = CR.doesContainReference();
491 }
492 if (isSelfInit) {
Ted Kremenekd40066b2011-04-04 23:29:12 +0000493 S.Diag(dr->getLocStart(),
494 diag::warn_uninit_self_reference_in_init)
495 << vd->getDeclName() << vd->getLocation() << dr->getSourceRange();
Chandler Carruthb414c4f2011-04-05 17:41:31 +0000496 } else {
Ted Kremenekd40066b2011-04-04 23:29:12 +0000497 S.Diag(dr->getLocStart(), diag::warn_uninit_var)
498 << vd->getDeclName() << dr->getSourceRange();
499 }
500 }
501 else {
502 S.Diag(dr->getLocStart(), diag::warn_maybe_uninit_var)
503 << vd->getDeclName() << dr->getSourceRange();
504 }
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000505 }
506 else {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000507 const BlockExpr *be = cast<BlockExpr>(vi->first);
508 S.Diag(be->getLocStart(),
509 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
510 : diag::warn_maybe_uninit_var_captured_by_block)
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000511 << vd->getDeclName();
512 }
Ted Kremenek609e3172011-02-02 23:35:53 +0000513
Chandler Carruthb414c4f2011-04-05 17:41:31 +0000514 // Report where the variable was declared when the use wasn't within
515 // the initializer of that declaration.
516 if (!isSelfInit)
Ted Kremenekd40066b2011-04-04 23:29:12 +0000517 S.Diag(vd->getLocStart(), diag::note_uninit_var_def)
518 << vd->getDeclName();
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000519
Ted Kremenek609e3172011-02-02 23:35:53 +0000520 // Only report the fixit once.
521 if (fixitIssued)
522 continue;
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000523
Ted Kremenek609e3172011-02-02 23:35:53 +0000524 fixitIssued = true;
Ted Kremenek5360c922011-04-04 19:43:57 +0000525
526 // Don't issue a fixit if there is already an initializer.
527 if (vd->getInit())
528 continue;
Ted Kremenek609e3172011-02-02 23:35:53 +0000529
530 // Suggest possible initialization (if any).
531 const char *initialization = 0;
532 QualType vdTy = vd->getType().getCanonicalType();
Ted Kremenek09f57b92011-02-05 01:18:18 +0000533
Ted Kremenek609e3172011-02-02 23:35:53 +0000534 if (vdTy->getAs<ObjCObjectPointerType>()) {
535 // Check if 'nil' is defined.
536 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
537 initialization = " = nil";
538 else
539 initialization = " = 0";
540 }
541 else if (vdTy->isRealFloatingType())
542 initialization = " = 0.0";
543 else if (vdTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
544 initialization = " = false";
Ted Kremenek09f57b92011-02-05 01:18:18 +0000545 else if (vdTy->isEnumeralType())
546 continue;
Ted Kremenek609e3172011-02-02 23:35:53 +0000547 else if (vdTy->isScalarType())
Ted Kremenekdcfb3602011-01-21 22:49:49 +0000548 initialization = " = 0";
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000549
Ted Kremenek609e3172011-02-02 23:35:53 +0000550 if (initialization) {
551 SourceLocation loc = S.PP.getLocForEndOfToken(vd->getLocEnd());
552 S.Diag(loc, diag::note_var_fixit_add_initialization)
553 << FixItHint::CreateInsertion(loc, initialization);
554 }
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000555 }
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000556 delete vec;
557 }
558 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000559 }
560};
561}
562
563//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000564// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
565// warnings on a function, method, or block.
566//===----------------------------------------------------------------------===//
567
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000568clang::sema::AnalysisBasedWarnings::Policy::Policy() {
569 enableCheckFallThrough = 1;
570 enableCheckUnreachable = 0;
571}
572
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000573clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
574 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000575 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000576 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
577 Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000578}
579
Ted Kremenek351ba912011-02-23 01:52:04 +0000580static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
581 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
582 i = fscope->PossiblyUnreachableDiags.begin(),
583 e = fscope->PossiblyUnreachableDiags.end();
584 i != e; ++i) {
585 const sema::PossiblyUnreachableDiag &D = *i;
586 S.Diag(D.Loc, D.PD);
587 }
588}
589
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000590void clang::sema::
591AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000592 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000593 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000594
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000595 // We avoid doing analysis-based warnings when there are errors for
596 // two reasons:
597 // (1) The CFGs often can't be constructed (if the body is invalid), so
598 // don't bother trying.
599 // (2) The code already has problems; running the analysis just takes more
600 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000601 Diagnostic &Diags = S.getDiagnostics();
602
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000603 // Do not do any analysis for declarations in system headers if we are
604 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000605 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000606 S.SourceMgr.isInSystemHeader(D->getLocation()))
607 return;
608
John McCalle0054f62010-08-25 05:56:39 +0000609 // For code in dependent contexts, we'll do this at instantiation time.
610 if (cast<DeclContext>(D)->isDependentContext())
611 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000612
Ted Kremenek351ba912011-02-23 01:52:04 +0000613 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
614 // Flush out any possibly unreachable diagnostics.
615 flushDiagnostics(S, fscope);
616 return;
617 }
618
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000619 const Stmt *Body = D->getBody();
620 assert(Body);
621
622 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
623 // explosion for destrutors that can result and the compile time hit.
Chandler Carrutheeef9242011-01-08 06:54:40 +0000624 AnalysisContext AC(D, 0, /*useUnoptimizedCFG=*/false, /*addehedges=*/false,
625 /*addImplicitDtors=*/true, /*addInitializers=*/true);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000626
Ted Kremenek351ba912011-02-23 01:52:04 +0000627 // Emit delayed diagnostics.
628 if (!fscope->PossiblyUnreachableDiags.empty()) {
629 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000630
631 // Register the expressions with the CFGBuilder.
632 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
633 i = fscope->PossiblyUnreachableDiags.begin(),
634 e = fscope->PossiblyUnreachableDiags.end();
635 i != e; ++i) {
636 if (const Stmt *stmt = i->stmt)
637 AC.registerForcedBlockExpression(stmt);
638 }
639
640 if (AC.getCFG()) {
641 analyzed = true;
642 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
643 i = fscope->PossiblyUnreachableDiags.begin(),
644 e = fscope->PossiblyUnreachableDiags.end();
645 i != e; ++i)
646 {
647 const sema::PossiblyUnreachableDiag &D = *i;
648 bool processed = false;
649 if (const Stmt *stmt = i->stmt) {
650 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
651 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000652 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000653 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000654 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000655 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000656 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000657 }
658 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000659 if (!processed) {
660 // Emit the warning anyway if we cannot map to a basic block.
661 S.Diag(D.Loc, D.PD);
662 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000663 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000664 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000665
666 if (!analyzed)
667 flushDiagnostics(S, fscope);
668 }
669
670
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000671 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000672 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000673 const CheckFallThroughDiagnostics &CD =
674 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000675 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000676 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000677 }
678
679 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000680 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000681 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +0000682
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000683 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +0000684 != Diagnostic::Ignored ||
685 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000686 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000687 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000688 UninitValsDiagReporter reporter(S);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000689 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
690 reporter);
Ted Kremenek610068c2011-01-15 02:58:47 +0000691 }
692 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000693}