blob: 823cbf74f55a0cd531c45bdcbb44fa7106c15109 [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"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000020#include "clang/Basic/SourceLocation.h"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000021#include "clang/Lex/Preprocessor.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000024#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000029#include "clang/AST/StmtVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000030#include "clang/Analysis/AnalysisContext.h"
31#include "clang/Analysis/CFG.h"
32#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000033#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000034#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000035#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000036#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000037#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000038#include "llvm/ADT/FoldingSet.h"
39#include "llvm/ADT/ImmutableMap.h"
40#include "llvm/ADT/PostOrderIterator.h"
41#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000042#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000043#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000044#include <algorithm>
45#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000046
47using namespace clang;
48
49//===----------------------------------------------------------------------===//
50// Unreachable code analysis.
51//===----------------------------------------------------------------------===//
52
53namespace {
54 class UnreachableCodeHandler : public reachable_code::Callback {
55 Sema &S;
56 public:
57 UnreachableCodeHandler(Sema &s) : S(s) {}
58
59 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
60 S.Diag(L, diag::warn_unreachable) << R1 << R2;
61 }
62 };
63}
64
65/// CheckUnreachable - Check for unreachable code.
66static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
67 UnreachableCodeHandler UC(S);
68 reachable_code::FindUnreachableCode(AC, UC);
69}
70
71//===----------------------------------------------------------------------===//
72// Check for missing return value.
73//===----------------------------------------------------------------------===//
74
John McCall16565aa2010-05-16 09:34:11 +000075enum ControlFlowKind {
76 UnknownFallThrough,
77 NeverFallThrough,
78 MaybeFallThrough,
79 AlwaysFallThrough,
80 NeverFallThroughOrReturn
81};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000082
83/// CheckFallThrough - Check that we don't fall off the end of a
84/// Statement that should return a value.
85///
86/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
87/// MaybeFallThrough iff we might or might not fall off the end,
88/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
89/// return. We assume NeverFallThrough iff we never fall off the end of the
90/// statement but we may return. We assume that functions not marked noreturn
91/// will return.
92static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
93 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000094 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000095
96 // The CFG leaves in dead things, and we don't want the dead code paths to
97 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000098 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +000099 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000100 live);
101
102 bool AddEHEdges = AC.getAddEHEdges();
103 if (!AddEHEdges && count != cfg->getNumBlockIDs())
104 // When there are things remaining dead, and we didn't add EH edges
105 // from CallExprs to the catch clauses, we have to go back and
106 // mark them as live.
107 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
108 CFGBlock &b = **I;
109 if (!live[b.getBlockID()]) {
110 if (b.pred_begin() == b.pred_end()) {
111 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
112 // When not adding EH edges from calls, catch clauses
113 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000114 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000115 continue;
116 }
117 }
118 }
119
120 // Now we know what is live, we check the live precessors of the exit block
121 // and look for fall through paths, being careful to ignore normal returns,
122 // and exceptional paths.
123 bool HasLiveReturn = false;
124 bool HasFakeEdge = false;
125 bool HasPlainEdge = false;
126 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000127
128 // Ignore default cases that aren't likely to be reachable because all
129 // enums in a switch(X) have explicit case statements.
130 CFGBlock::FilterOptions FO;
131 FO.IgnoreDefaultsWithCoveredEnums = 1;
132
133 for (CFGBlock::filtered_pred_iterator
134 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
135 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000136 if (!live[B.getBlockID()])
137 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000138
139 // Destructors can appear after the 'return' in the CFG. This is
140 // normal. We need to look pass the destructors for the return
141 // statement (if it exists).
142 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000143 bool hasNoReturnDtor = false;
144
Ted Kremenek5811f592011-01-26 04:49:52 +0000145 for ( ; ri != re ; ++ri) {
146 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000147
148 // FIXME: The right solution is to just sever the edges in the
149 // CFG itself.
150 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
Ted Kremenekc5aff442011-03-03 01:21:32 +0000151 if (iDtor->isNoReturn(AC.getASTContext())) {
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000152 hasNoReturnDtor = true;
153 HasFakeEdge = true;
154 break;
155 }
156
Ted Kremenek5811f592011-01-26 04:49:52 +0000157 if (isa<CFGStmt>(CE))
158 break;
159 }
160
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000161 if (hasNoReturnDtor)
162 continue;
163
Ted Kremenek5811f592011-01-26 04:49:52 +0000164 // No more CFGElements in the block?
165 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000166 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
167 HasAbnormalEdge = true;
168 continue;
169 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000170 // A labeled empty statement, or the entry block...
171 HasPlainEdge = true;
172 continue;
173 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000174
Ted Kremenek5811f592011-01-26 04:49:52 +0000175 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000176 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000177 if (isa<ReturnStmt>(S)) {
178 HasLiveReturn = true;
179 continue;
180 }
181 if (isa<ObjCAtThrowStmt>(S)) {
182 HasFakeEdge = true;
183 continue;
184 }
185 if (isa<CXXThrowExpr>(S)) {
186 HasFakeEdge = true;
187 continue;
188 }
189 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
190 if (AS->isMSAsm()) {
191 HasFakeEdge = true;
192 HasLiveReturn = true;
193 continue;
194 }
195 }
196 if (isa<CXXTryStmt>(S)) {
197 HasAbnormalEdge = true;
198 continue;
199 }
200
201 bool NoReturnEdge = false;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000202 if (const CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000203 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
204 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000205 HasAbnormalEdge = true;
206 continue;
207 }
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000208 const Expr *CEE = C->getCallee()->IgnoreParenCasts();
John McCall1de85332011-05-11 07:19:11 +0000209 QualType calleeType = CEE->getType();
210 if (calleeType == AC.getASTContext().BoundMemberTy) {
211 calleeType = Expr::findBoundMemberType(CEE);
212 assert(!calleeType.isNull() && "analyzing unresolved call?");
213 }
214 if (getFunctionExtInfo(calleeType).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000215 NoReturnEdge = true;
216 HasFakeEdge = true;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000217 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
218 const ValueDecl *VD = DRE->getDecl();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000219 if (VD->hasAttr<NoReturnAttr>()) {
220 NoReturnEdge = true;
221 HasFakeEdge = true;
222 }
223 }
224 }
225 // FIXME: Add noreturn message sends.
226 if (NoReturnEdge == false)
227 HasPlainEdge = true;
228 }
229 if (!HasPlainEdge) {
230 if (HasLiveReturn)
231 return NeverFallThrough;
232 return NeverFallThroughOrReturn;
233 }
234 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
235 return MaybeFallThrough;
236 // This says AlwaysFallThrough for calls to functions that are not marked
237 // noreturn, that don't return. If people would like this warning to be more
238 // accurate, such functions should be marked as noreturn.
239 return AlwaysFallThrough;
240}
241
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000242namespace {
243
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000244struct CheckFallThroughDiagnostics {
245 unsigned diag_MaybeFallThrough_HasNoReturn;
246 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
247 unsigned diag_AlwaysFallThrough_HasNoReturn;
248 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
249 unsigned diag_NeverFallThroughOrReturn;
250 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000251 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000252
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000253 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000254 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000255 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000256 D.diag_MaybeFallThrough_HasNoReturn =
257 diag::warn_falloff_noreturn_function;
258 D.diag_MaybeFallThrough_ReturnsNonVoid =
259 diag::warn_maybe_falloff_nonvoid_function;
260 D.diag_AlwaysFallThrough_HasNoReturn =
261 diag::warn_falloff_noreturn_function;
262 D.diag_AlwaysFallThrough_ReturnsNonVoid =
263 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000264
265 // Don't suggest that virtual functions be marked "noreturn", since they
266 // might be overridden by non-noreturn functions.
267 bool isVirtualMethod = false;
268 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
269 isVirtualMethod = Method->isVirtual();
270
271 if (!isVirtualMethod)
272 D.diag_NeverFallThroughOrReturn =
273 diag::warn_suggest_noreturn_function;
274 else
275 D.diag_NeverFallThroughOrReturn = 0;
276
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000277 D.funMode = true;
278 return D;
279 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000280
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000281 static CheckFallThroughDiagnostics MakeForBlock() {
282 CheckFallThroughDiagnostics D;
283 D.diag_MaybeFallThrough_HasNoReturn =
284 diag::err_noreturn_block_has_return_expr;
285 D.diag_MaybeFallThrough_ReturnsNonVoid =
286 diag::err_maybe_falloff_nonvoid_block;
287 D.diag_AlwaysFallThrough_HasNoReturn =
288 diag::err_noreturn_block_has_return_expr;
289 D.diag_AlwaysFallThrough_ReturnsNonVoid =
290 diag::err_falloff_nonvoid_block;
291 D.diag_NeverFallThroughOrReturn =
292 diag::warn_suggest_noreturn_block;
293 D.funMode = false;
294 return D;
295 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000296
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000297 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
298 bool HasNoReturn) const {
299 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000300 return (ReturnsVoid ||
301 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
302 FuncLoc) == Diagnostic::Ignored)
303 && (!HasNoReturn ||
304 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
305 FuncLoc) == Diagnostic::Ignored)
306 && (!ReturnsVoid ||
307 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
308 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000309 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000310
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000311 // For blocks.
312 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000313 && (!ReturnsVoid ||
314 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
315 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000316 }
317};
318
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000319}
320
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000321/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
322/// function that should return a value. Check that we don't fall off the end
323/// of a noreturn function. We assume that functions and blocks not marked
324/// noreturn will return.
325static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000326 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000327 const CheckFallThroughDiagnostics& CD,
328 AnalysisContext &AC) {
329
330 bool ReturnsVoid = false;
331 bool HasNoReturn = false;
332
333 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
334 ReturnsVoid = FD->getResultType()->isVoidType();
335 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000336 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000337 }
338 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
339 ReturnsVoid = MD->getResultType()->isVoidType();
340 HasNoReturn = MD->hasAttr<NoReturnAttr>();
341 }
342 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000343 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000344 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000345 BlockTy->getPointeeType()->getAs<FunctionType>()) {
346 if (FT->getResultType()->isVoidType())
347 ReturnsVoid = true;
348 if (FT->getNoReturnAttr())
349 HasNoReturn = true;
350 }
351 }
352
353 Diagnostic &Diags = S.getDiagnostics();
354
355 // Short circuit for compilation speed.
356 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
357 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000358
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000359 // FIXME: Function try block
360 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
361 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000362 case UnknownFallThrough:
363 break;
364
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000365 case MaybeFallThrough:
366 if (HasNoReturn)
367 S.Diag(Compound->getRBracLoc(),
368 CD.diag_MaybeFallThrough_HasNoReturn);
369 else if (!ReturnsVoid)
370 S.Diag(Compound->getRBracLoc(),
371 CD.diag_MaybeFallThrough_ReturnsNonVoid);
372 break;
373 case AlwaysFallThrough:
374 if (HasNoReturn)
375 S.Diag(Compound->getRBracLoc(),
376 CD.diag_AlwaysFallThrough_HasNoReturn);
377 else if (!ReturnsVoid)
378 S.Diag(Compound->getRBracLoc(),
379 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
380 break;
381 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000382 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
383 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
384 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
385 << FD;
386 } else {
387 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
388 }
389 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000390 break;
391 case NeverFallThrough:
392 break;
393 }
394 }
395}
396
397//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000398// -Wuninitialized
399//===----------------------------------------------------------------------===//
400
Ted Kremenek6f417152011-04-04 20:56:00 +0000401namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000402/// ContainsReference - A visitor class to search for references to
403/// a particular declaration (the needle) within any evaluated component of an
404/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000405class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000406 bool FoundReference;
407 const DeclRefExpr *Needle;
408
Ted Kremenek6f417152011-04-04 20:56:00 +0000409public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000410 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
411 : EvaluatedExprVisitor<ContainsReference>(Context),
412 FoundReference(false), Needle(Needle) {}
413
414 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000415 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000416 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000417 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000418
419 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000420 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000421
422 void VisitDeclRefExpr(DeclRefExpr *E) {
423 if (E == Needle)
424 FoundReference = true;
425 else
426 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000427 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000428
429 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000430};
431}
432
Chandler Carruth262d50e2011-04-05 18:27:05 +0000433/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
434/// uninitialized variable. This manages the different forms of diagnostic
435/// emitted for particular types of uses. Returns true if the use was diagnosed
436/// as a warning. If a pariticular use is one we omit warnings for, returns
437/// false.
438static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Chandler Carruth64fb9592011-04-05 18:18:08 +0000439 const Expr *E, bool isAlwaysUninit) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000440 bool isSelfInit = false;
441
442 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
443 if (isAlwaysUninit) {
444 // Inspect the initializer of the variable declaration which is
445 // being referenced prior to its initialization. We emit
446 // specialized diagnostics for self-initialization, and we
447 // specifically avoid warning about self references which take the
448 // form of:
449 //
450 // int x = x;
451 //
452 // This is used to indicate to GCC that 'x' is intentionally left
453 // uninitialized. Proven code paths which access 'x' in
454 // an uninitialized state after this will still warn.
455 //
456 // TODO: Should we suppress maybe-uninitialized warnings for
457 // variables initialized in this way?
458 if (const Expr *Initializer = VD->getInit()) {
459 if (DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000460 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000461
462 ContainsReference CR(S.Context, DRE);
463 CR.Visit(const_cast<Expr*>(Initializer));
464 isSelfInit = CR.doesContainReference();
465 }
466 if (isSelfInit) {
467 S.Diag(DRE->getLocStart(),
468 diag::warn_uninit_self_reference_in_init)
469 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
470 } else {
471 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
472 << VD->getDeclName() << DRE->getSourceRange();
473 }
474 } else {
475 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
476 << VD->getDeclName() << DRE->getSourceRange();
477 }
478 } else {
479 const BlockExpr *BE = cast<BlockExpr>(E);
480 S.Diag(BE->getLocStart(),
481 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
482 : diag::warn_maybe_uninit_var_captured_by_block)
483 << VD->getDeclName();
484 }
485
486 // Report where the variable was declared when the use wasn't within
487 // the initializer of that declaration.
488 if (!isSelfInit)
489 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
490 << VD->getDeclName();
491
Chandler Carruth262d50e2011-04-05 18:27:05 +0000492 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000493}
494
Chandler Carruth262d50e2011-04-05 18:27:05 +0000495static void SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000496 // Don't issue a fixit if there is already an initializer.
497 if (VD->getInit())
498 return;
499
500 // Suggest possible initialization (if any).
501 const char *initialization = 0;
502 QualType VariableTy = VD->getType().getCanonicalType();
503
Douglas Gregor8ba44262011-07-02 00:59:18 +0000504 if (VariableTy->isObjCObjectPointerType() ||
505 VariableTy->isBlockPointerType()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000506 // Check if 'nil' is defined.
507 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
508 initialization = " = nil";
509 else
510 initialization = " = 0";
511 }
512 else if (VariableTy->isRealFloatingType())
513 initialization = " = 0.0";
514 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
515 initialization = " = false";
516 else if (VariableTy->isEnumeralType())
517 return;
Douglas Gregor8ba44262011-07-02 00:59:18 +0000518 else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType()) {
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000519 if (S.Context.getLangOptions().CPlusPlus0x)
520 initialization = " = nullptr";
Douglas Gregor8ba44262011-07-02 00:59:18 +0000521 // Check if 'NULL' is defined.
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000522 else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL")))
Douglas Gregor8ba44262011-07-02 00:59:18 +0000523 initialization = " = NULL";
524 else
525 initialization = " = 0";
526 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000527 else if (VariableTy->isScalarType())
528 initialization = " = 0";
529
530 if (initialization) {
531 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
532 S.Diag(loc, diag::note_var_fixit_add_initialization)
533 << FixItHint::CreateInsertion(loc, initialization);
534 }
535}
536
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000537typedef std::pair<const Expr*, bool> UninitUse;
538
Ted Kremenek610068c2011-01-15 02:58:47 +0000539namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000540struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000541 bool operator()(const UninitUse &a, const UninitUse &b) {
542 SourceLocation aLoc = a.first->getLocStart();
543 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000544 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
545 }
546};
547
Ted Kremenek610068c2011-01-15 02:58:47 +0000548class UninitValsDiagReporter : public UninitVariablesHandler {
549 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000550 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000551 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
552 UsesMap *uses;
553
Ted Kremenek610068c2011-01-15 02:58:47 +0000554public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000555 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
556 ~UninitValsDiagReporter() {
557 flushDiagnostics();
558 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000559
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000560 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
561 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000562 if (!uses)
563 uses = new UsesMap();
564
565 UsesVec *&vec = (*uses)[vd];
566 if (!vec)
567 vec = new UsesVec();
568
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000569 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000570 }
571
572 void flushDiagnostics() {
573 if (!uses)
574 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000575
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000576 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
577 const VarDecl *vd = i->first;
578 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000579
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000580 // Sort the uses by their SourceLocations. While not strictly
581 // guaranteed to produce them in line/column order, this will provide
582 // a stable ordering.
583 std::sort(vec->begin(), vec->end(), SLocSort());
584
Chandler Carruth64fb9592011-04-05 18:18:08 +0000585 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
586 ++vi) {
Chandler Carruth262d50e2011-04-05 18:27:05 +0000587 if (!DiagnoseUninitializedUse(S, vd, vi->first,
588 /*isAlwaysUninit=*/vi->second))
589 continue;
590
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000591 SuggestInitializationFixit(S, vd);
592
593 // Skip further diagnostics for this variable. We try to warn only on
594 // the first point at which a variable is used uninitialized.
595 break;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000596 }
Ted Kremenekd40066b2011-04-04 23:29:12 +0000597
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000598 delete vec;
599 }
600 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000601 }
602};
603}
604
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000605
606//===----------------------------------------------------------------------===//
607// -Wthread-safety
608//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000609namespace clang {
610namespace thread_safety {
611typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag;
612typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
613
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000614struct SortDiagBySourceLocation {
615 Sema &S;
616 SortDiagBySourceLocation(Sema &S) : S(S) {}
617
618 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
619 // Although this call will be slow, this is only called when outputting
620 // multiple warnings.
621 return S.getSourceManager().isBeforeInTranslationUnit(left.first,
622 right.first);
623 }
624};
625
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000626class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
627 Sema &S;
628 DiagList Warnings;
629
630 // Helper functions
631 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
632 PartialDiagnostic Warning = S.PDiag(DiagID) << LockName;
633 Warnings.push_back(DelayedDiag(Loc, Warning));
634 }
635
636 public:
637 ThreadSafetyReporter(Sema &S) : S(S) {}
638
639 /// \brief Emit all buffered diagnostics in order of sourcelocation.
640 /// We need to output diagnostics produced while iterating through
641 /// the lockset in deterministic order, so this function orders diagnostics
642 /// and outputs them.
643 void emitDiagnostics() {
644 SortDiagBySourceLocation SortDiagBySL(S);
645 sort(Warnings.begin(), Warnings.end(), SortDiagBySL);
646 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
647 I != E; ++I)
648 S.Diag(I->first, I->second);
649 }
650
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000651 void handleInvalidLockExp(SourceLocation Loc) {
652 PartialDiagnostic Warning = S.PDiag(diag::warn_cannot_resolve_lock) << Loc;
653 Warnings.push_back(DelayedDiag(Loc, Warning));
654 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000655 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
656 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
657 }
658
659 void handleDoubleLock(Name LockName, SourceLocation Loc) {
660 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
661 }
662
663 void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc){
664 warnLockMismatch(diag::warn_lock_at_end_of_scope, LockName, Loc);
665 }
666
667 void handleNoLockLoopEntry(Name LockName, SourceLocation Loc) {
668 warnLockMismatch(diag::warn_expecting_lock_held_on_loop, LockName, Loc);
669 }
670
671 void handleNoUnlock(Name LockName, llvm::StringRef FunName,
672 SourceLocation Loc) {
673 PartialDiagnostic Warning =
674 S.PDiag(diag::warn_no_unlock) << LockName << FunName;
675 Warnings.push_back(DelayedDiag(Loc, Warning));
676 }
677
678 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
679 SourceLocation Loc2) {
680 PartialDiagnostic Warning =
681 S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName;
682 PartialDiagnostic Note =
683 S.PDiag(diag::note_lock_exclusive_and_shared) << LockName;
684 Warnings.push_back(DelayedDiag(Loc1, Warning));
685 Warnings.push_back(DelayedDiag(Loc2, Note));
686 }
687
688 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
689 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskia49d1d82011-09-09 16:07:55 +0000690 // FIXME: It would be nice if this case printed without single quotes around
691 // the phrase 'any mutex'
692 handleMutexNotHeld(D, POK, "any mutex", getLockKindFromAccessKind(AK), Loc);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000693 }
694
695 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
696 Name LockName, LockKind LK, SourceLocation Loc) {
697 unsigned DiagID;
698 switch (POK) {
699 case POK_VarAccess:
700 DiagID = diag::warn_variable_requires_lock;
701 break;
702 case POK_VarDereference:
703 DiagID = diag::warn_var_deref_requires_lock;
704 break;
705 case POK_FunctionCall:
706 DiagID = diag::warn_fun_requires_lock;
707 break;
708 }
709 PartialDiagnostic Warning = S.PDiag(DiagID)
710 << D->getName().str() << LockName << LK;
711 Warnings.push_back(DelayedDiag(Loc, Warning));
712 }
713
714 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
715 PartialDiagnostic Warning =
716 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName;
717 Warnings.push_back(DelayedDiag(Loc, Warning));
718 }
719};
720}
721}
722
Ted Kremenek610068c2011-01-15 02:58:47 +0000723//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000724// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
725// warnings on a function, method, or block.
726//===----------------------------------------------------------------------===//
727
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000728clang::sema::AnalysisBasedWarnings::Policy::Policy() {
729 enableCheckFallThrough = 1;
730 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000731 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000732}
733
Chandler Carruth5d989942011-07-06 16:21:37 +0000734clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
735 : S(s),
736 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000737 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +0000738 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000739 MaxCFGBlocksPerFunction(0),
740 NumUninitAnalysisFunctions(0),
741 NumUninitAnalysisVariables(0),
742 MaxUninitAnalysisVariablesPerFunction(0),
743 NumUninitAnalysisBlockVisits(0),
744 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000745 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000746 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000747 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
748 Diagnostic::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000749 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
750 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
751 Diagnostic::Ignored);
752
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000753}
754
Ted Kremenek351ba912011-02-23 01:52:04 +0000755static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000756 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +0000757 i = fscope->PossiblyUnreachableDiags.begin(),
758 e = fscope->PossiblyUnreachableDiags.end();
759 i != e; ++i) {
760 const sema::PossiblyUnreachableDiag &D = *i;
761 S.Diag(D.Loc, D.PD);
762 }
763}
764
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000765void clang::sema::
766AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000767 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000768 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000769
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000770 // We avoid doing analysis-based warnings when there are errors for
771 // two reasons:
772 // (1) The CFGs often can't be constructed (if the body is invalid), so
773 // don't bother trying.
774 // (2) The code already has problems; running the analysis just takes more
775 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +0000776 Diagnostic &Diags = S.getDiagnostics();
777
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000778 // Do not do any analysis for declarations in system headers if we are
779 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000780 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000781 S.SourceMgr.isInSystemHeader(D->getLocation()))
782 return;
783
John McCalle0054f62010-08-25 05:56:39 +0000784 // For code in dependent contexts, we'll do this at instantiation time.
785 if (cast<DeclContext>(D)->isDependentContext())
786 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000787
Ted Kremenek351ba912011-02-23 01:52:04 +0000788 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
789 // Flush out any possibly unreachable diagnostics.
790 flushDiagnostics(S, fscope);
791 return;
792 }
793
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000794 const Stmt *Body = D->getBody();
795 assert(Body);
796
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000797 AnalysisContext AC(D, 0);
798
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000799 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
800 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000801 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
802 AC.getCFGBuildOptions().AddEHEdges = false;
803 AC.getCFGBuildOptions().AddInitializers = true;
804 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000805
806 // Force that certain expressions appear as CFGElements in the CFG. This
807 // is used to speed up various analyses.
808 // FIXME: This isn't the right factoring. This is here for initial
809 // prototyping, but we need a way for analyses to say what expressions they
810 // expect to always be CFGElements and then fill in the BuildOptions
811 // appropriately. This is essentially a layering violation.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000812 if (P.enableCheckUnreachable) {
813 // Unreachable code analysis requires a linearized CFG.
814 AC.getCFGBuildOptions().setAllAlwaysAdd();
815 }
816 else {
817 AC.getCFGBuildOptions()
818 .setAlwaysAdd(Stmt::BinaryOperatorClass)
819 .setAlwaysAdd(Stmt::BlockExprClass)
820 .setAlwaysAdd(Stmt::CStyleCastExprClass)
821 .setAlwaysAdd(Stmt::DeclRefExprClass)
822 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
823 .setAlwaysAdd(Stmt::UnaryOperatorClass);
824 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000825
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000826 // Construct the analysis context with the specified CFG build options.
827
Ted Kremenek351ba912011-02-23 01:52:04 +0000828 // Emit delayed diagnostics.
829 if (!fscope->PossiblyUnreachableDiags.empty()) {
830 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000831
832 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000833 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000834 i = fscope->PossiblyUnreachableDiags.begin(),
835 e = fscope->PossiblyUnreachableDiags.end();
836 i != e; ++i) {
837 if (const Stmt *stmt = i->stmt)
838 AC.registerForcedBlockExpression(stmt);
839 }
840
841 if (AC.getCFG()) {
842 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000843 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000844 i = fscope->PossiblyUnreachableDiags.begin(),
845 e = fscope->PossiblyUnreachableDiags.end();
846 i != e; ++i)
847 {
848 const sema::PossiblyUnreachableDiag &D = *i;
849 bool processed = false;
850 if (const Stmt *stmt = i->stmt) {
851 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
852 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000853 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000854 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000855 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000856 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000857 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000858 }
859 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000860 if (!processed) {
861 // Emit the warning anyway if we cannot map to a basic block.
862 S.Diag(D.Loc, D.PD);
863 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000864 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000865 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000866
867 if (!analyzed)
868 flushDiagnostics(S, fscope);
869 }
870
871
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000872 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000873 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000874 const CheckFallThroughDiagnostics &CD =
875 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000876 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000877 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000878 }
879
880 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000881 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000882 CheckUnreachable(S, AC);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000883
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000884 // Check for thread safety violations
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000885 if (P.enableThreadSafetyAnalysis) {
886 thread_safety::ThreadSafetyReporter Reporter(S);
887 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
888 Reporter.emitDiagnostics();
889 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000890
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000891 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +0000892 != Diagnostic::Ignored ||
893 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +0000894 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000895 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000896 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +0000897 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +0000898 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000899 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +0000900 reporter, stats);
901
902 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
903 ++NumUninitAnalysisFunctions;
904 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
905 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
906 MaxUninitAnalysisVariablesPerFunction =
907 std::max(MaxUninitAnalysisVariablesPerFunction,
908 stats.NumVariablesAnalyzed);
909 MaxUninitAnalysisBlockVisitsPerFunction =
910 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
911 stats.NumBlockVisits);
912 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000913 }
914 }
Chandler Carruth5d989942011-07-06 16:21:37 +0000915
916 // Collect statistics about the CFG if it was built.
917 if (S.CollectStats && AC.isCFGBuilt()) {
918 ++NumFunctionsAnalyzed;
919 if (CFG *cfg = AC.getCFG()) {
920 // If we successfully built a CFG for this context, record some more
921 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000922 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +0000923 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000924 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +0000925 } else {
926 ++NumFunctionsWithBadCFGs;
927 }
928 }
929}
930
931void clang::sema::AnalysisBasedWarnings::PrintStats() const {
932 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
933
934 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
935 unsigned AvgCFGBlocksPerFunction =
936 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
937 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
938 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
939 << " " << NumCFGBlocks << " CFG blocks built.\n"
940 << " " << AvgCFGBlocksPerFunction
941 << " average CFG blocks per function.\n"
942 << " " << MaxCFGBlocksPerFunction
943 << " max CFG blocks per function.\n";
944
945 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
946 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
947 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
948 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
949 llvm::errs() << NumUninitAnalysisFunctions
950 << " functions analyzed for uninitialiazed variables\n"
951 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
952 << " " << AvgUninitVariablesPerFunction
953 << " average variables per function.\n"
954 << " " << MaxUninitAnalysisVariablesPerFunction
955 << " max variables per function.\n"
956 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
957 << " " << AvgUninitBlockVisitsPerFunction
958 << " average block visits per function.\n"
959 << " " << MaxUninitAnalysisBlockVisitsPerFunction
960 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000961}