blob: 84efbd50d1a5b807567f91a59aa43fe1ca56ad6e [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();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000132 bool hasNoReturnDtor = false;
133
Ted Kremenek5811f592011-01-26 04:49:52 +0000134 for ( ; ri != re ; ++ri) {
135 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000136
137 // FIXME: The right solution is to just sever the edges in the
138 // CFG itself.
139 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
140 if (iDtor->isNoReturn()) {
141 hasNoReturnDtor = true;
142 HasFakeEdge = true;
143 break;
144 }
145
Ted Kremenek5811f592011-01-26 04:49:52 +0000146 if (isa<CFGStmt>(CE))
147 break;
148 }
149
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000150 if (hasNoReturnDtor)
151 continue;
152
Ted Kremenek5811f592011-01-26 04:49:52 +0000153 // No more CFGElements in the block?
154 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000155 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
156 HasAbnormalEdge = true;
157 continue;
158 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000159 // A labeled empty statement, or the entry block...
160 HasPlainEdge = true;
161 continue;
162 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000163
Ted Kremenek5811f592011-01-26 04:49:52 +0000164 CFGStmt CS = cast<CFGStmt>(*ri);
Zhongxing Xub36cd3e2010-09-16 01:25:47 +0000165 Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000166 if (isa<ReturnStmt>(S)) {
167 HasLiveReturn = true;
168 continue;
169 }
170 if (isa<ObjCAtThrowStmt>(S)) {
171 HasFakeEdge = true;
172 continue;
173 }
174 if (isa<CXXThrowExpr>(S)) {
175 HasFakeEdge = true;
176 continue;
177 }
178 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
179 if (AS->isMSAsm()) {
180 HasFakeEdge = true;
181 HasLiveReturn = true;
182 continue;
183 }
184 }
185 if (isa<CXXTryStmt>(S)) {
186 HasAbnormalEdge = true;
187 continue;
188 }
189
190 bool NoReturnEdge = false;
191 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000192 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
193 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000194 HasAbnormalEdge = true;
195 continue;
196 }
197 Expr *CEE = C->getCallee()->IgnoreParenCasts();
Rafael Espindola264ba482010-03-30 20:24:48 +0000198 if (getFunctionExtInfo(CEE->getType()).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000199 NoReturnEdge = true;
200 HasFakeEdge = true;
201 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
202 ValueDecl *VD = DRE->getDecl();
203 if (VD->hasAttr<NoReturnAttr>()) {
204 NoReturnEdge = true;
205 HasFakeEdge = true;
206 }
207 }
208 }
209 // FIXME: Add noreturn message sends.
210 if (NoReturnEdge == false)
211 HasPlainEdge = true;
212 }
213 if (!HasPlainEdge) {
214 if (HasLiveReturn)
215 return NeverFallThrough;
216 return NeverFallThroughOrReturn;
217 }
218 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
219 return MaybeFallThrough;
220 // This says AlwaysFallThrough for calls to functions that are not marked
221 // noreturn, that don't return. If people would like this warning to be more
222 // accurate, such functions should be marked as noreturn.
223 return AlwaysFallThrough;
224}
225
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000226namespace {
227
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000228struct CheckFallThroughDiagnostics {
229 unsigned diag_MaybeFallThrough_HasNoReturn;
230 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
231 unsigned diag_AlwaysFallThrough_HasNoReturn;
232 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
233 unsigned diag_NeverFallThroughOrReturn;
234 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000235 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000236
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000237 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000238 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000239 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000240 D.diag_MaybeFallThrough_HasNoReturn =
241 diag::warn_falloff_noreturn_function;
242 D.diag_MaybeFallThrough_ReturnsNonVoid =
243 diag::warn_maybe_falloff_nonvoid_function;
244 D.diag_AlwaysFallThrough_HasNoReturn =
245 diag::warn_falloff_noreturn_function;
246 D.diag_AlwaysFallThrough_ReturnsNonVoid =
247 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000248
249 // Don't suggest that virtual functions be marked "noreturn", since they
250 // might be overridden by non-noreturn functions.
251 bool isVirtualMethod = false;
252 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
253 isVirtualMethod = Method->isVirtual();
254
255 if (!isVirtualMethod)
256 D.diag_NeverFallThroughOrReturn =
257 diag::warn_suggest_noreturn_function;
258 else
259 D.diag_NeverFallThroughOrReturn = 0;
260
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000261 D.funMode = true;
262 return D;
263 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000264
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000265 static CheckFallThroughDiagnostics MakeForBlock() {
266 CheckFallThroughDiagnostics D;
267 D.diag_MaybeFallThrough_HasNoReturn =
268 diag::err_noreturn_block_has_return_expr;
269 D.diag_MaybeFallThrough_ReturnsNonVoid =
270 diag::err_maybe_falloff_nonvoid_block;
271 D.diag_AlwaysFallThrough_HasNoReturn =
272 diag::err_noreturn_block_has_return_expr;
273 D.diag_AlwaysFallThrough_ReturnsNonVoid =
274 diag::err_falloff_nonvoid_block;
275 D.diag_NeverFallThroughOrReturn =
276 diag::warn_suggest_noreturn_block;
277 D.funMode = false;
278 return D;
279 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000280
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000281 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
282 bool HasNoReturn) const {
283 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000284 return (ReturnsVoid ||
285 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
286 FuncLoc) == Diagnostic::Ignored)
287 && (!HasNoReturn ||
288 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
289 FuncLoc) == Diagnostic::Ignored)
290 && (!ReturnsVoid ||
291 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
292 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000293 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000294
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000295 // For blocks.
296 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000297 && (!ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
299 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000300 }
301};
302
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000303}
304
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000305/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
306/// function that should return a value. Check that we don't fall off the end
307/// of a noreturn function. We assume that functions and blocks not marked
308/// noreturn will return.
309static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000310 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000311 const CheckFallThroughDiagnostics& CD,
312 AnalysisContext &AC) {
313
314 bool ReturnsVoid = false;
315 bool HasNoReturn = false;
316
317 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
318 ReturnsVoid = FD->getResultType()->isVoidType();
319 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000320 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000321 }
322 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
323 ReturnsVoid = MD->getResultType()->isVoidType();
324 HasNoReturn = MD->hasAttr<NoReturnAttr>();
325 }
326 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000327 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000328 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000329 BlockTy->getPointeeType()->getAs<FunctionType>()) {
330 if (FT->getResultType()->isVoidType())
331 ReturnsVoid = true;
332 if (FT->getNoReturnAttr())
333 HasNoReturn = true;
334 }
335 }
336
337 Diagnostic &Diags = S.getDiagnostics();
338
339 // Short circuit for compilation speed.
340 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
341 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000342
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000343 // FIXME: Function try block
344 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
345 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000346 case UnknownFallThrough:
347 break;
348
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000349 case MaybeFallThrough:
350 if (HasNoReturn)
351 S.Diag(Compound->getRBracLoc(),
352 CD.diag_MaybeFallThrough_HasNoReturn);
353 else if (!ReturnsVoid)
354 S.Diag(Compound->getRBracLoc(),
355 CD.diag_MaybeFallThrough_ReturnsNonVoid);
356 break;
357 case AlwaysFallThrough:
358 if (HasNoReturn)
359 S.Diag(Compound->getRBracLoc(),
360 CD.diag_AlwaysFallThrough_HasNoReturn);
361 else if (!ReturnsVoid)
362 S.Diag(Compound->getRBracLoc(),
363 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
364 break;
365 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000366 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000367 S.Diag(Compound->getLBracLoc(),
368 CD.diag_NeverFallThroughOrReturn);
369 break;
370 case NeverFallThrough:
371 break;
372 }
373 }
374}
375
376//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000377// -Wuninitialized
378//===----------------------------------------------------------------------===//
379
380namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000381struct SLocSort {
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000382 bool operator()(const Expr *a, const Expr *b) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000383 SourceLocation aLoc = a->getLocStart();
384 SourceLocation bLoc = b->getLocStart();
385 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
386 }
387};
388
Ted Kremenek610068c2011-01-15 02:58:47 +0000389class UninitValsDiagReporter : public UninitVariablesHandler {
390 Sema &S;
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000391 typedef llvm::SmallVector<const Expr *, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000392 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
393 UsesMap *uses;
394
Ted Kremenek610068c2011-01-15 02:58:47 +0000395public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000396 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
397 ~UninitValsDiagReporter() {
398 flushDiagnostics();
399 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000400
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000401 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000402 if (!uses)
403 uses = new UsesMap();
404
405 UsesVec *&vec = (*uses)[vd];
406 if (!vec)
407 vec = new UsesVec();
408
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000409 vec->push_back(ex);
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000410 }
411
412 void flushDiagnostics() {
413 if (!uses)
414 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000415
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000416 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
417 const VarDecl *vd = i->first;
418 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000419
420 bool fixitIssued = false;
421
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000422 // Sort the uses by their SourceLocations. While not strictly
423 // guaranteed to produce them in line/column order, this will provide
424 // a stable ordering.
425 std::sort(vec->begin(), vec->end(), SLocSort());
426
427 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve; ++vi)
428 {
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000429 if (const DeclRefExpr *dr = dyn_cast<DeclRefExpr>(*vi)) {
Ted Kremenek609e3172011-02-02 23:35:53 +0000430 S.Diag(dr->getLocStart(), diag::warn_uninit_var)
431 << vd->getDeclName() << dr->getSourceRange();
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000432 }
433 else {
434 const BlockExpr *be = cast<BlockExpr>(*vi);
Ted Kremenek609e3172011-02-02 23:35:53 +0000435 S.Diag(be->getLocStart(), diag::warn_uninit_var_captured_by_block)
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000436 << vd->getDeclName();
437 }
Ted Kremenek609e3172011-02-02 23:35:53 +0000438
439 // Report where the variable was declared.
440 S.Diag(vd->getLocStart(), diag::note_uninit_var_def)
441 << vd->getDeclName();
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000442
Ted Kremenek609e3172011-02-02 23:35:53 +0000443 // Only report the fixit once.
444 if (fixitIssued)
445 continue;
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000446
Ted Kremenek609e3172011-02-02 23:35:53 +0000447 fixitIssued = true;
448
449 // Suggest possible initialization (if any).
450 const char *initialization = 0;
451 QualType vdTy = vd->getType().getCanonicalType();
Ted Kremenek09f57b92011-02-05 01:18:18 +0000452
Ted Kremenek609e3172011-02-02 23:35:53 +0000453 if (vdTy->getAs<ObjCObjectPointerType>()) {
454 // Check if 'nil' is defined.
455 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
456 initialization = " = nil";
457 else
458 initialization = " = 0";
459 }
460 else if (vdTy->isRealFloatingType())
461 initialization = " = 0.0";
462 else if (vdTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
463 initialization = " = false";
Ted Kremenek09f57b92011-02-05 01:18:18 +0000464 else if (vdTy->isEnumeralType())
465 continue;
Ted Kremenek609e3172011-02-02 23:35:53 +0000466 else if (vdTy->isScalarType())
Ted Kremenekdcfb3602011-01-21 22:49:49 +0000467 initialization = " = 0";
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000468
Ted Kremenek609e3172011-02-02 23:35:53 +0000469 if (initialization) {
470 SourceLocation loc = S.PP.getLocForEndOfToken(vd->getLocEnd());
471 S.Diag(loc, diag::note_var_fixit_add_initialization)
472 << FixItHint::CreateInsertion(loc, initialization);
473 }
Ted Kremenekfbb178a2011-01-21 19:41:46 +0000474 }
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000475 delete vec;
476 }
477 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000478 }
479};
480}
481
482//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000483// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
484// warnings on a function, method, or block.
485//===----------------------------------------------------------------------===//
486
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000487clang::sema::AnalysisBasedWarnings::Policy::Policy() {
488 enableCheckFallThrough = 1;
489 enableCheckUnreachable = 0;
490}
491
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000492clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) {
493 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000494 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000495 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
496 Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000497}
498
Ted Kremenek351ba912011-02-23 01:52:04 +0000499static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
500 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
501 i = fscope->PossiblyUnreachableDiags.begin(),
502 e = fscope->PossiblyUnreachableDiags.end();
503 i != e; ++i) {
504 const sema::PossiblyUnreachableDiag &D = *i;
505 S.Diag(D.Loc, D.PD);
506 }
507}
508
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000509void clang::sema::
510AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000511 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000512 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000513
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000514 // We avoid doing analysis-based warnings when there are errors for
515 // two reasons:
516 // (1) The CFGs often can't be constructed (if the body is invalid), so
517 // don't bother trying.
518 // (2) The code already has problems; running the analysis just takes more
519 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000520 Diagnostic &Diags = S.getDiagnostics();
521
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000522 // Do not do any analysis for declarations in system headers if we are
523 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000524 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000525 S.SourceMgr.isInSystemHeader(D->getLocation()))
526 return;
527
John McCalle0054f62010-08-25 05:56:39 +0000528 // For code in dependent contexts, we'll do this at instantiation time.
529 if (cast<DeclContext>(D)->isDependentContext())
530 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000531
Ted Kremenek351ba912011-02-23 01:52:04 +0000532 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
533 // Flush out any possibly unreachable diagnostics.
534 flushDiagnostics(S, fscope);
535 return;
536 }
537
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000538 const Stmt *Body = D->getBody();
539 assert(Body);
540
541 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
542 // explosion for destrutors that can result and the compile time hit.
Chandler Carrutheeef9242011-01-08 06:54:40 +0000543 AnalysisContext AC(D, 0, /*useUnoptimizedCFG=*/false, /*addehedges=*/false,
544 /*addImplicitDtors=*/true, /*addInitializers=*/true);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000545
Ted Kremenek351ba912011-02-23 01:52:04 +0000546 // Emit delayed diagnostics.
547 if (!fscope->PossiblyUnreachableDiags.empty()) {
548 bool analyzed = false;
549 if (CFGReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis())
550 if (CFGStmtMap *csm = AC.getCFGStmtMap()) {
551 analyzed = true;
552 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
553 i = fscope->PossiblyUnreachableDiags.begin(),
554 e = fscope->PossiblyUnreachableDiags.end();
555 i != e; ++i) {
556 const sema::PossiblyUnreachableDiag &D = *i;
557 if (const CFGBlock *blk = csm->getBlock(D.stmt)) {
558 // Can this block be reached from the entrance?
559 if (cra->isReachable(&AC.getCFG()->getEntry(), blk))
560 S.Diag(D.Loc, D.PD);
561 }
562 else {
563 // Emit the warning anyway if we cannot map to a basic block.
564 S.Diag(D.Loc, D.PD);
565 }
566 }
567 }
568
569 if (!analyzed)
570 flushDiagnostics(S, fscope);
571 }
572
573
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000574 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000575 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000576 const CheckFallThroughDiagnostics &CD =
577 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000578 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000579 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000580 }
581
582 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000583 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000584 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +0000585
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000586 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000587 != Diagnostic::Ignored) {
Ted Kremenek63b54102011-02-01 17:43:21 +0000588 ASTContext &ctx = D->getASTContext();
589 llvm::OwningPtr<CFG> tmpCFG;
590 bool useAlternateCFG = false;
591 if (ctx.getLangOptions().CPlusPlus) {
592 // Temporary workaround: implicit dtors in the CFG can confuse
593 // the path-sensitivity in the uninitialized values analysis.
594 // For now create (if necessary) a separate CFG without implicit dtors.
595 // FIXME: We should not need to do this, as it results in multiple
596 // CFGs getting constructed.
597 CFG::BuildOptions B;
598 B.AddEHEdges = false;
599 B.AddImplicitDtors = false;
600 B.AddInitializers = true;
601 tmpCFG.reset(CFG::buildCFG(D, AC.getBody(), &ctx, B));
602 useAlternateCFG = true;
603 }
604 CFG *cfg = useAlternateCFG ? tmpCFG.get() : AC.getCFG();
605 if (cfg) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000606 UninitValsDiagReporter reporter(S);
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000607 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
608 reporter);
Ted Kremenek610068c2011-01-15 02:58:47 +0000609 }
610 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000611}