blob: 6a422242a9d4d9bd69da42d278488545b1ebd9fa [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"
27#include "clang/Analysis/AnalysisContext.h"
28#include "clang/Analysis/CFG.h"
29#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000030#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
31#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek610068c2011-01-15 02:58:47 +000032#include "clang/Analysis/Analyses/UninitializedValuesV2.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000033#include "llvm/ADT/BitVector.h"
34#include "llvm/Support/Casting.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000035
36using namespace clang;
37
38//===----------------------------------------------------------------------===//
39// Unreachable code analysis.
40//===----------------------------------------------------------------------===//
41
42namespace {
43 class UnreachableCodeHandler : public reachable_code::Callback {
44 Sema &S;
45 public:
46 UnreachableCodeHandler(Sema &s) : S(s) {}
47
48 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
49 S.Diag(L, diag::warn_unreachable) << R1 << R2;
50 }
51 };
52}
53
54/// CheckUnreachable - Check for unreachable code.
55static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
56 UnreachableCodeHandler UC(S);
57 reachable_code::FindUnreachableCode(AC, UC);
58}
59
60//===----------------------------------------------------------------------===//
61// Check for missing return value.
62//===----------------------------------------------------------------------===//
63
John McCall16565aa2010-05-16 09:34:11 +000064enum ControlFlowKind {
65 UnknownFallThrough,
66 NeverFallThrough,
67 MaybeFallThrough,
68 AlwaysFallThrough,
69 NeverFallThroughOrReturn
70};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000071
72/// CheckFallThrough - Check that we don't fall off the end of a
73/// Statement that should return a value.
74///
75/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
76/// MaybeFallThrough iff we might or might not fall off the end,
77/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
78/// return. We assume NeverFallThrough iff we never fall off the end of the
79/// statement but we may return. We assume that functions not marked noreturn
80/// will return.
81static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
82 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000083 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000084
85 // The CFG leaves in dead things, and we don't want the dead code paths to
86 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000087 llvm::BitVector live(cfg->getNumBlockIDs());
88 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
89 live);
90
91 bool AddEHEdges = AC.getAddEHEdges();
92 if (!AddEHEdges && count != cfg->getNumBlockIDs())
93 // When there are things remaining dead, and we didn't add EH edges
94 // from CallExprs to the catch clauses, we have to go back and
95 // mark them as live.
96 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
97 CFGBlock &b = **I;
98 if (!live[b.getBlockID()]) {
99 if (b.pred_begin() == b.pred_end()) {
100 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
101 // When not adding EH edges from calls, catch clauses
102 // can otherwise seem dead. Avoid noting them as dead.
103 count += reachable_code::ScanReachableFromBlock(b, live);
104 continue;
105 }
106 }
107 }
108
109 // Now we know what is live, we check the live precessors of the exit block
110 // and look for fall through paths, being careful to ignore normal returns,
111 // and exceptional paths.
112 bool HasLiveReturn = false;
113 bool HasFakeEdge = false;
114 bool HasPlainEdge = false;
115 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000116
117 // Ignore default cases that aren't likely to be reachable because all
118 // enums in a switch(X) have explicit case statements.
119 CFGBlock::FilterOptions FO;
120 FO.IgnoreDefaultsWithCoveredEnums = 1;
121
122 for (CFGBlock::filtered_pred_iterator
123 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
124 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000125 if (!live[B.getBlockID()])
126 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000127
128 // Destructors can appear after the 'return' in the CFG. This is
129 // normal. We need to look pass the destructors for the return
130 // statement (if it exists).
131 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
132 for ( ; ri != re ; ++ri) {
133 CFGElement CE = *ri;
134 if (isa<CFGStmt>(CE))
135 break;
136 }
137
138 // No more CFGElements in the block?
139 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000140 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
141 HasAbnormalEdge = true;
142 continue;
143 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000144 // A labeled empty statement, or the entry block...
145 HasPlainEdge = true;
146 continue;
147 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000148
Ted Kremenek5811f592011-01-26 04:49:52 +0000149 CFGStmt CS = cast<CFGStmt>(*ri);
Zhongxing Xub36cd3e2010-09-16 01:25:47 +0000150 Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000151 if (isa<ReturnStmt>(S)) {
152 HasLiveReturn = true;
153 continue;
154 }
155 if (isa<ObjCAtThrowStmt>(S)) {
156 HasFakeEdge = true;
157 continue;
158 }
159 if (isa<CXXThrowExpr>(S)) {
160 HasFakeEdge = true;
161 continue;
162 }
163 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
164 if (AS->isMSAsm()) {
165 HasFakeEdge = true;
166 HasLiveReturn = true;
167 continue;
168 }
169 }
170 if (isa<CXXTryStmt>(S)) {
171 HasAbnormalEdge = true;
172 continue;
173 }
174
175 bool NoReturnEdge = false;
176 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000177 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
178 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000179 HasAbnormalEdge = true;
180 continue;
181 }
182 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Rafael Espindola264ba482010-03-30 20:24:48 +0000183 if (getFunctionExtInfo(CEE->getType()).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000184 NoReturnEdge = true;
185 HasFakeEdge = true;
186 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
187 ValueDecl *VD = DRE->getDecl();
188 if (VD->hasAttr<NoReturnAttr>()) {
189 NoReturnEdge = true;
190 HasFakeEdge = true;
191 }
192 }
193 }
194 // FIXME: Add noreturn message sends.
195 if (NoReturnEdge == false)
196 HasPlainEdge = true;
197 }
198 if (!HasPlainEdge) {
199 if (HasLiveReturn)
200 return NeverFallThrough;
201 return NeverFallThroughOrReturn;
202 }
203 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
204 return MaybeFallThrough;
205 // This says AlwaysFallThrough for calls to functions that are not marked
206 // noreturn, that don't return. If people would like this warning to be more
207 // accurate, such functions should be marked as noreturn.
208 return AlwaysFallThrough;
209}
210
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000211namespace {
212
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000213struct CheckFallThroughDiagnostics {
214 unsigned diag_MaybeFallThrough_HasNoReturn;
215 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
216 unsigned diag_AlwaysFallThrough_HasNoReturn;
217 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
218 unsigned diag_NeverFallThroughOrReturn;
219 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000220 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000221
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000222 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000223 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000224 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000225 D.diag_MaybeFallThrough_HasNoReturn =
226 diag::warn_falloff_noreturn_function;
227 D.diag_MaybeFallThrough_ReturnsNonVoid =
228 diag::warn_maybe_falloff_nonvoid_function;
229 D.diag_AlwaysFallThrough_HasNoReturn =
230 diag::warn_falloff_noreturn_function;
231 D.diag_AlwaysFallThrough_ReturnsNonVoid =
232 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000233
234 // Don't suggest that virtual functions be marked "noreturn", since they
235 // might be overridden by non-noreturn functions.
236 bool isVirtualMethod = false;
237 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
238 isVirtualMethod = Method->isVirtual();
239
240 if (!isVirtualMethod)
241 D.diag_NeverFallThroughOrReturn =
242 diag::warn_suggest_noreturn_function;
243 else
244 D.diag_NeverFallThroughOrReturn = 0;
245
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000246 D.funMode = true;
247 return D;
248 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000249
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000250 static CheckFallThroughDiagnostics MakeForBlock() {
251 CheckFallThroughDiagnostics D;
252 D.diag_MaybeFallThrough_HasNoReturn =
253 diag::err_noreturn_block_has_return_expr;
254 D.diag_MaybeFallThrough_ReturnsNonVoid =
255 diag::err_maybe_falloff_nonvoid_block;
256 D.diag_AlwaysFallThrough_HasNoReturn =
257 diag::err_noreturn_block_has_return_expr;
258 D.diag_AlwaysFallThrough_ReturnsNonVoid =
259 diag::err_falloff_nonvoid_block;
260 D.diag_NeverFallThroughOrReturn =
261 diag::warn_suggest_noreturn_block;
262 D.funMode = false;
263 return D;
264 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000265
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000266 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
267 bool HasNoReturn) const {
268 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000269 return (ReturnsVoid ||
270 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
271 FuncLoc) == Diagnostic::Ignored)
272 && (!HasNoReturn ||
273 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
274 FuncLoc) == Diagnostic::Ignored)
275 && (!ReturnsVoid ||
276 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
277 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000278 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000279
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000280 // For blocks.
281 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000282 && (!ReturnsVoid ||
283 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
284 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000285 }
286};
287
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000288}
289
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000290/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
291/// function that should return a value. Check that we don't fall off the end
292/// of a noreturn function. We assume that functions and blocks not marked
293/// noreturn will return.
294static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000295 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000296 const CheckFallThroughDiagnostics& CD,
297 AnalysisContext &AC) {
298
299 bool ReturnsVoid = false;
300 bool HasNoReturn = false;
301
302 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
303 ReturnsVoid = FD->getResultType()->isVoidType();
304 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000305 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000306 }
307 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
308 ReturnsVoid = MD->getResultType()->isVoidType();
309 HasNoReturn = MD->hasAttr<NoReturnAttr>();
310 }
311 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000312 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000313 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000314 BlockTy->getPointeeType()->getAs<FunctionType>()) {
315 if (FT->getResultType()->isVoidType())
316 ReturnsVoid = true;
317 if (FT->getNoReturnAttr())
318 HasNoReturn = true;
319 }
320 }
321
322 Diagnostic &Diags = S.getDiagnostics();
323
324 // Short circuit for compilation speed.
325 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
326 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000327
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000328 // FIXME: Function try block
329 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
330 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000331 case UnknownFallThrough:
332 break;
333
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000334 case MaybeFallThrough:
335 if (HasNoReturn)
336 S.Diag(Compound->getRBracLoc(),
337 CD.diag_MaybeFallThrough_HasNoReturn);
338 else if (!ReturnsVoid)
339 S.Diag(Compound->getRBracLoc(),
340 CD.diag_MaybeFallThrough_ReturnsNonVoid);
341 break;
342 case AlwaysFallThrough:
343 if (HasNoReturn)
344 S.Diag(Compound->getRBracLoc(),
345 CD.diag_AlwaysFallThrough_HasNoReturn);
346 else if (!ReturnsVoid)
347 S.Diag(Compound->getRBracLoc(),
348 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
349 break;
350 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000351 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000352 S.Diag(Compound->getLBracLoc(),
353 CD.diag_NeverFallThroughOrReturn);
354 break;
355 case NeverFallThrough:
356 break;
357 }
358 }
359}
360
361//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000362// -Wuninitialized
363//===----------------------------------------------------------------------===//
364
365namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000366struct SLocSort {
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000367 bool operator()(const Expr *a, const Expr *b) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000368 SourceLocation aLoc = a->getLocStart();
369 SourceLocation bLoc = b->getLocStart();
370 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
371 }
372};
373
Ted Kremenek610068c2011-01-15 02:58:47 +0000374class UninitValsDiagReporter : public UninitVariablesHandler {
375 Sema &S;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000376 typedef llvm::SmallVector<const Expr *, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000377 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
378 UsesMap *uses;
379
Ted Kremenek610068c2011-01-15 02:58:47 +0000380public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000381 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
382 ~UninitValsDiagReporter() {
383 flushDiagnostics();
384 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000385
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000386 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000387 if (!uses)
388 uses = new UsesMap();
389
390 UsesVec *&vec = (*uses)[vd];
391 if (!vec)
392 vec = new UsesVec();
393
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000394 vec->push_back(ex);
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000395 }
396
397 void flushDiagnostics() {
398 if (!uses)
399 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000400
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000401 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
402 const VarDecl *vd = i->first;
403 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000404
405 bool fixitIssued = false;
406
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000407 // Sort the uses by their SourceLocations. While not strictly
408 // guaranteed to produce them in line/column order, this will provide
409 // a stable ordering.
410 std::sort(vec->begin(), vec->end(), SLocSort());
411
412 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve; ++vi)
413 {
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000414 if (const DeclRefExpr *dr = dyn_cast<DeclRefExpr>(*vi)) {
Ted Kremenek609e3172011-02-02 23:35:53 +0000415 S.Diag(dr->getLocStart(), diag::warn_uninit_var)
416 << vd->getDeclName() << dr->getSourceRange();
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000417 }
418 else {
419 const BlockExpr *be = cast<BlockExpr>(*vi);
Ted Kremenek609e3172011-02-02 23:35:53 +0000420 S.Diag(be->getLocStart(), diag::warn_uninit_var_captured_by_block)
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000421 << vd->getDeclName();
422 }
Ted Kremenek609e3172011-02-02 23:35:53 +0000423
424 // Report where the variable was declared.
425 S.Diag(vd->getLocStart(), diag::note_uninit_var_def)
426 << vd->getDeclName();
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000427
Ted Kremenek609e3172011-02-02 23:35:53 +0000428 // Only report the fixit once.
429 if (fixitIssued)
430 continue;
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000431
Ted Kremenek609e3172011-02-02 23:35:53 +0000432 fixitIssued = true;
433
434 // Suggest possible initialization (if any).
435 const char *initialization = 0;
436 QualType vdTy = vd->getType().getCanonicalType();
Ted Kremenek09f57b92011-02-05 01:18:18 +0000437
Ted Kremenek609e3172011-02-02 23:35:53 +0000438 if (vdTy->getAs<ObjCObjectPointerType>()) {
439 // Check if 'nil' is defined.
440 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
441 initialization = " = nil";
442 else
443 initialization = " = 0";
444 }
445 else if (vdTy->isRealFloatingType())
446 initialization = " = 0.0";
447 else if (vdTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
448 initialization = " = false";
Ted Kremenek09f57b92011-02-05 01:18:18 +0000449 else if (vdTy->isEnumeralType())
450 continue;
Ted Kremenek609e3172011-02-02 23:35:53 +0000451 else if (vdTy->isScalarType())
Ted Kremenekdcfb3602011-01-21 22:49:49 +0000452 initialization = " = 0";
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000453
Ted Kremenek609e3172011-02-02 23:35:53 +0000454 if (initialization) {
455 SourceLocation loc = S.PP.getLocForEndOfToken(vd->getLocEnd());
456 S.Diag(loc, diag::note_var_fixit_add_initialization)
457 << FixItHint::CreateInsertion(loc, initialization);
458 }
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000459 }
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000460 delete vec;
461 }
462 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000463 }
464};
465}
466
467//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000468// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
469// warnings on a function, method, or block.
470//===----------------------------------------------------------------------===//
471
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000472clang::sema::AnalysisBasedWarnings::Policy::Policy() {
473 enableCheckFallThrough = 1;
474 enableCheckUnreachable = 0;
475}
476
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000477clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
478 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000479 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000480 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
481 Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000482}
483
Ted Kremenek351ba912011-02-23 01:52:04 +0000484static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
485 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
486 i = fscope->PossiblyUnreachableDiags.begin(),
487 e = fscope->PossiblyUnreachableDiags.end();
488 i != e; ++i) {
489 const sema::PossiblyUnreachableDiag &D = *i;
490 S.Diag(D.Loc, D.PD);
491 }
492}
493
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000494void clang::sema::
495AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000496 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000497 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000498
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000499 // We avoid doing analysis-based warnings when there are errors for
500 // two reasons:
501 // (1) The CFGs often can't be constructed (if the body is invalid), so
502 // don't bother trying.
503 // (2) The code already has problems; running the analysis just takes more
504 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000505 Diagnostic &Diags = S.getDiagnostics();
506
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000507 // Do not do any analysis for declarations in system headers if we are
508 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000509 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000510 S.SourceMgr.isInSystemHeader(D->getLocation()))
511 return;
512
John McCalle0054f62010-08-25 05:56:39 +0000513 // For code in dependent contexts, we'll do this at instantiation time.
514 if (cast<DeclContext>(D)->isDependentContext())
515 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000516
Ted Kremenek351ba912011-02-23 01:52:04 +0000517 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
518 // Flush out any possibly unreachable diagnostics.
519 flushDiagnostics(S, fscope);
520 return;
521 }
522
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000523 const Stmt *Body = D->getBody();
524 assert(Body);
525
526 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
527 // explosion for destrutors that can result and the compile time hit.
Chandler Carrutheeef9242011-01-08 06:54:40 +0000528 AnalysisContext AC(D, 0, /*useUnoptimizedCFG=*/false, /*addehedges=*/false,
529 /*addImplicitDtors=*/true, /*addInitializers=*/true);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000530
Ted Kremenek351ba912011-02-23 01:52:04 +0000531 // Emit delayed diagnostics.
532 if (!fscope->PossiblyUnreachableDiags.empty()) {
533 bool analyzed = false;
534 if (CFGReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis())
535 if (CFGStmtMap *csm = AC.getCFGStmtMap()) {
536 analyzed = true;
537 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
538 i = fscope->PossiblyUnreachableDiags.begin(),
539 e = fscope->PossiblyUnreachableDiags.end();
540 i != e; ++i) {
541 const sema::PossiblyUnreachableDiag &D = *i;
542 if (const CFGBlock *blk = csm->getBlock(D.stmt)) {
543 // Can this block be reached from the entrance?
544 if (cra->isReachable(&AC.getCFG()->getEntry(), blk))
545 S.Diag(D.Loc, D.PD);
546 }
547 else {
548 // Emit the warning anyway if we cannot map to a basic block.
549 S.Diag(D.Loc, D.PD);
550 }
551 }
552 }
553
554 if (!analyzed)
555 flushDiagnostics(S, fscope);
556 }
557
558
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000559 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000560 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000561 const CheckFallThroughDiagnostics &CD =
562 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000563 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000564 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000565 }
566
567 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000568 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000569 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +0000570
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000571 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000572 != Diagnostic::Ignored) {
Ted Kremenek63b54102011-02-01 17:43:21 +0000573 ASTContext &ctx = D->getASTContext();
574 llvm::OwningPtr<CFG> tmpCFG;
575 bool useAlternateCFG = false;
576 if (ctx.getLangOptions().CPlusPlus) {
577 // Temporary workaround: implicit dtors in the CFG can confuse
578 // the path-sensitivity in the uninitialized values analysis.
579 // For now create (if necessary) a separate CFG without implicit dtors.
580 // FIXME: We should not need to do this, as it results in multiple
581 // CFGs getting constructed.
582 CFG::BuildOptions B;
583 B.AddEHEdges = false;
584 B.AddImplicitDtors = false;
585 B.AddInitializers = true;
586 tmpCFG.reset(CFG::buildCFG(D, AC.getBody(), &ctx, B));
587 useAlternateCFG = true;
588 }
589 CFG *cfg = useAlternateCFG ? tmpCFG.get() : AC.getCFG();
590 if (cfg) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000591 UninitValsDiagReporter reporter(S);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000592 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
593 reporter);
Ted Kremenek610068c2011-01-15 02:58:47 +0000594 }
595 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000596}