blob: f461772ba7d4fe6a3be11440dea2cd56086d7033 [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
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000139 // Skip blocks which contain an element marked as no-return. They don't
140 // represent actually viable edges into the exit block, so mark them as
141 // abnormal.
142 if (B.hasNoReturnElement()) {
143 HasAbnormalEdge = true;
144 continue;
145 }
146
Ted Kremenek5811f592011-01-26 04:49:52 +0000147 // Destructors can appear after the 'return' in the CFG. This is
148 // normal. We need to look pass the destructors for the return
149 // statement (if it exists).
150 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000151
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000152 for ( ; ri != re ; ++ri)
153 if (isa<CFGStmt>(*ri))
Ted Kremenek5811f592011-01-26 04:49:52 +0000154 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000155
Ted Kremenek5811f592011-01-26 04:49:52 +0000156 // No more CFGElements in the block?
157 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000158 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
159 HasAbnormalEdge = true;
160 continue;
161 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000162 // A labeled empty statement, or the entry block...
163 HasPlainEdge = true;
164 continue;
165 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000166
Ted Kremenek5811f592011-01-26 04:49:52 +0000167 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000168 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000169 if (isa<ReturnStmt>(S)) {
170 HasLiveReturn = true;
171 continue;
172 }
173 if (isa<ObjCAtThrowStmt>(S)) {
174 HasFakeEdge = true;
175 continue;
176 }
177 if (isa<CXXThrowExpr>(S)) {
178 HasFakeEdge = true;
179 continue;
180 }
181 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
182 if (AS->isMSAsm()) {
183 HasFakeEdge = true;
184 HasLiveReturn = true;
185 continue;
186 }
187 }
188 if (isa<CXXTryStmt>(S)) {
189 HasAbnormalEdge = true;
190 continue;
191 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000192 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
193 == B.succ_end()) {
194 HasAbnormalEdge = true;
195 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000196 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000197
198 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000199 }
200 if (!HasPlainEdge) {
201 if (HasLiveReturn)
202 return NeverFallThrough;
203 return NeverFallThroughOrReturn;
204 }
205 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
206 return MaybeFallThrough;
207 // This says AlwaysFallThrough for calls to functions that are not marked
208 // noreturn, that don't return. If people would like this warning to be more
209 // accurate, such functions should be marked as noreturn.
210 return AlwaysFallThrough;
211}
212
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000213namespace {
214
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000215struct CheckFallThroughDiagnostics {
216 unsigned diag_MaybeFallThrough_HasNoReturn;
217 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
218 unsigned diag_AlwaysFallThrough_HasNoReturn;
219 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
220 unsigned diag_NeverFallThroughOrReturn;
221 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000222 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000223
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000224 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000225 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000226 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000227 D.diag_MaybeFallThrough_HasNoReturn =
228 diag::warn_falloff_noreturn_function;
229 D.diag_MaybeFallThrough_ReturnsNonVoid =
230 diag::warn_maybe_falloff_nonvoid_function;
231 D.diag_AlwaysFallThrough_HasNoReturn =
232 diag::warn_falloff_noreturn_function;
233 D.diag_AlwaysFallThrough_ReturnsNonVoid =
234 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000235
236 // Don't suggest that virtual functions be marked "noreturn", since they
237 // might be overridden by non-noreturn functions.
238 bool isVirtualMethod = false;
239 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
240 isVirtualMethod = Method->isVirtual();
241
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000242 // Don't suggest that template instantiations be marked "noreturn"
243 bool isTemplateInstantiation = false;
244 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func)) {
245 switch (Function->getTemplateSpecializationKind()) {
246 case TSK_Undeclared:
247 case TSK_ExplicitSpecialization:
248 break;
249
250 case TSK_ImplicitInstantiation:
251 case TSK_ExplicitInstantiationDeclaration:
252 case TSK_ExplicitInstantiationDefinition:
253 isTemplateInstantiation = true;
254 break;
255 }
256 }
257
258 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000259 D.diag_NeverFallThroughOrReturn =
260 diag::warn_suggest_noreturn_function;
261 else
262 D.diag_NeverFallThroughOrReturn = 0;
263
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000264 D.funMode = true;
265 return D;
266 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000267
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000268 static CheckFallThroughDiagnostics MakeForBlock() {
269 CheckFallThroughDiagnostics D;
270 D.diag_MaybeFallThrough_HasNoReturn =
271 diag::err_noreturn_block_has_return_expr;
272 D.diag_MaybeFallThrough_ReturnsNonVoid =
273 diag::err_maybe_falloff_nonvoid_block;
274 D.diag_AlwaysFallThrough_HasNoReturn =
275 diag::err_noreturn_block_has_return_expr;
276 D.diag_AlwaysFallThrough_ReturnsNonVoid =
277 diag::err_falloff_nonvoid_block;
278 D.diag_NeverFallThroughOrReturn =
279 diag::warn_suggest_noreturn_block;
280 D.funMode = false;
281 return D;
282 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000283
David Blaikied6471f72011-09-25 23:23:43 +0000284 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000285 bool HasNoReturn) const {
286 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000287 return (ReturnsVoid ||
288 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000289 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000290 && (!HasNoReturn ||
291 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000292 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000293 && (!ReturnsVoid ||
294 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000295 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000296 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000297
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000298 // For blocks.
299 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000300 && (!ReturnsVoid ||
301 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000302 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000303 }
304};
305
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000306}
307
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000308/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
309/// function that should return a value. Check that we don't fall off the end
310/// of a noreturn function. We assume that functions and blocks not marked
311/// noreturn will return.
312static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000313 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000314 const CheckFallThroughDiagnostics& CD,
315 AnalysisContext &AC) {
316
317 bool ReturnsVoid = false;
318 bool HasNoReturn = false;
319
320 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
321 ReturnsVoid = FD->getResultType()->isVoidType();
322 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000323 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000324 }
325 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
326 ReturnsVoid = MD->getResultType()->isVoidType();
327 HasNoReturn = MD->hasAttr<NoReturnAttr>();
328 }
329 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000330 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000331 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000332 BlockTy->getPointeeType()->getAs<FunctionType>()) {
333 if (FT->getResultType()->isVoidType())
334 ReturnsVoid = true;
335 if (FT->getNoReturnAttr())
336 HasNoReturn = true;
337 }
338 }
339
David Blaikied6471f72011-09-25 23:23:43 +0000340 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000341
342 // Short circuit for compilation speed.
343 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
344 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000345
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000346 // FIXME: Function try block
347 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
348 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000349 case UnknownFallThrough:
350 break;
351
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000352 case MaybeFallThrough:
353 if (HasNoReturn)
354 S.Diag(Compound->getRBracLoc(),
355 CD.diag_MaybeFallThrough_HasNoReturn);
356 else if (!ReturnsVoid)
357 S.Diag(Compound->getRBracLoc(),
358 CD.diag_MaybeFallThrough_ReturnsNonVoid);
359 break;
360 case AlwaysFallThrough:
361 if (HasNoReturn)
362 S.Diag(Compound->getRBracLoc(),
363 CD.diag_AlwaysFallThrough_HasNoReturn);
364 else if (!ReturnsVoid)
365 S.Diag(Compound->getRBracLoc(),
366 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
367 break;
368 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000369 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
370 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
371 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000372 << 0 << FD;
373 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
374 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
375 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000376 } else {
377 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
378 }
379 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000380 break;
381 case NeverFallThrough:
382 break;
383 }
384 }
385}
386
387//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000388// -Wuninitialized
389//===----------------------------------------------------------------------===//
390
Ted Kremenek6f417152011-04-04 20:56:00 +0000391namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000392/// ContainsReference - A visitor class to search for references to
393/// a particular declaration (the needle) within any evaluated component of an
394/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000395class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000396 bool FoundReference;
397 const DeclRefExpr *Needle;
398
Ted Kremenek6f417152011-04-04 20:56:00 +0000399public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000400 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
401 : EvaluatedExprVisitor<ContainsReference>(Context),
402 FoundReference(false), Needle(Needle) {}
403
404 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000405 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000406 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000407 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000408
409 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000410 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000411
412 void VisitDeclRefExpr(DeclRefExpr *E) {
413 if (E == Needle)
414 FoundReference = true;
415 else
416 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000417 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000418
419 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000420};
421}
422
David Blaikie4f4f3492011-09-10 05:35:08 +0000423static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
424 // Don't issue a fixit if there is already an initializer.
425 if (VD->getInit())
426 return false;
427
428 // Suggest possible initialization (if any).
429 const char *initialization = 0;
430 QualType VariableTy = VD->getType().getCanonicalType();
431
432 if (VariableTy->isObjCObjectPointerType() ||
433 VariableTy->isBlockPointerType()) {
434 // Check if 'nil' is defined.
435 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
436 initialization = " = nil";
437 else
438 initialization = " = 0";
439 }
440 else if (VariableTy->isRealFloatingType())
441 initialization = " = 0.0";
442 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
443 initialization = " = false";
444 else if (VariableTy->isEnumeralType())
445 return false;
446 else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType()) {
447 if (S.Context.getLangOptions().CPlusPlus0x)
448 initialization = " = nullptr";
449 // Check if 'NULL' is defined.
450 else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL")))
451 initialization = " = NULL";
452 else
453 initialization = " = 0";
454 }
455 else if (VariableTy->isScalarType())
456 initialization = " = 0";
457
458 if (initialization) {
459 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
460 S.Diag(loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
461 << FixItHint::CreateInsertion(loc, initialization);
462 return true;
463 }
464 return false;
465}
466
Chandler Carruth262d50e2011-04-05 18:27:05 +0000467/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
468/// uninitialized variable. This manages the different forms of diagnostic
469/// emitted for particular types of uses. Returns true if the use was diagnosed
470/// as a warning. If a pariticular use is one we omit warnings for, returns
471/// false.
472static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Chandler Carruth64fb9592011-04-05 18:18:08 +0000473 const Expr *E, bool isAlwaysUninit) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000474 bool isSelfInit = false;
475
476 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
477 if (isAlwaysUninit) {
478 // Inspect the initializer of the variable declaration which is
479 // being referenced prior to its initialization. We emit
480 // specialized diagnostics for self-initialization, and we
481 // specifically avoid warning about self references which take the
482 // form of:
483 //
484 // int x = x;
485 //
486 // This is used to indicate to GCC that 'x' is intentionally left
487 // uninitialized. Proven code paths which access 'x' in
488 // an uninitialized state after this will still warn.
489 //
490 // TODO: Should we suppress maybe-uninitialized warnings for
491 // variables initialized in this way?
492 if (const Expr *Initializer = VD->getInit()) {
493 if (DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000494 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000495
496 ContainsReference CR(S.Context, DRE);
497 CR.Visit(const_cast<Expr*>(Initializer));
498 isSelfInit = CR.doesContainReference();
499 }
500 if (isSelfInit) {
501 S.Diag(DRE->getLocStart(),
502 diag::warn_uninit_self_reference_in_init)
503 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
504 } else {
505 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
506 << VD->getDeclName() << DRE->getSourceRange();
507 }
508 } else {
509 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
510 << VD->getDeclName() << DRE->getSourceRange();
511 }
512 } else {
513 const BlockExpr *BE = cast<BlockExpr>(E);
514 S.Diag(BE->getLocStart(),
515 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
516 : diag::warn_maybe_uninit_var_captured_by_block)
517 << VD->getDeclName();
518 }
519
520 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000521 // the initializer of that declaration & we didn't already suggest
522 // an initialization fixit.
523 if (!isSelfInit && !SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000524 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
525 << VD->getDeclName();
526
Chandler Carruth262d50e2011-04-05 18:27:05 +0000527 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000528}
529
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000530typedef std::pair<const Expr*, bool> UninitUse;
531
Ted Kremenek610068c2011-01-15 02:58:47 +0000532namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000533struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000534 bool operator()(const UninitUse &a, const UninitUse &b) {
535 SourceLocation aLoc = a.first->getLocStart();
536 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000537 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
538 }
539};
540
Ted Kremenek610068c2011-01-15 02:58:47 +0000541class UninitValsDiagReporter : public UninitVariablesHandler {
542 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000543 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000544 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
545 UsesMap *uses;
546
Ted Kremenek610068c2011-01-15 02:58:47 +0000547public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000548 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
549 ~UninitValsDiagReporter() {
550 flushDiagnostics();
551 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000552
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000553 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
554 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000555 if (!uses)
556 uses = new UsesMap();
557
558 UsesVec *&vec = (*uses)[vd];
559 if (!vec)
560 vec = new UsesVec();
561
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000562 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000563 }
564
565 void flushDiagnostics() {
566 if (!uses)
567 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000568
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000569 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
570 const VarDecl *vd = i->first;
571 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000572
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000573 // Sort the uses by their SourceLocations. While not strictly
574 // guaranteed to produce them in line/column order, this will provide
575 // a stable ordering.
576 std::sort(vec->begin(), vec->end(), SLocSort());
577
Chandler Carruth64fb9592011-04-05 18:18:08 +0000578 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
579 ++vi) {
David Blaikie4f4f3492011-09-10 05:35:08 +0000580 if (DiagnoseUninitializedUse(S, vd, vi->first,
Chandler Carruth262d50e2011-04-05 18:27:05 +0000581 /*isAlwaysUninit=*/vi->second))
David Blaikie4f4f3492011-09-10 05:35:08 +0000582 // Skip further diagnostics for this variable. We try to warn only on
583 // the first point at which a variable is used uninitialized.
584 break;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000585 }
Ted Kremenekd40066b2011-04-04 23:29:12 +0000586
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000587 delete vec;
588 }
589 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000590 }
591};
592}
593
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000594
595//===----------------------------------------------------------------------===//
596// -Wthread-safety
597//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000598namespace clang {
599namespace thread_safety {
600typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag;
601typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
602
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000603struct SortDiagBySourceLocation {
604 Sema &S;
605 SortDiagBySourceLocation(Sema &S) : S(S) {}
606
607 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
608 // Although this call will be slow, this is only called when outputting
609 // multiple warnings.
610 return S.getSourceManager().isBeforeInTranslationUnit(left.first,
611 right.first);
612 }
613};
614
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000615class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
616 Sema &S;
617 DiagList Warnings;
618
619 // Helper functions
620 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
621 PartialDiagnostic Warning = S.PDiag(DiagID) << LockName;
622 Warnings.push_back(DelayedDiag(Loc, Warning));
623 }
624
625 public:
626 ThreadSafetyReporter(Sema &S) : S(S) {}
627
628 /// \brief Emit all buffered diagnostics in order of sourcelocation.
629 /// We need to output diagnostics produced while iterating through
630 /// the lockset in deterministic order, so this function orders diagnostics
631 /// and outputs them.
632 void emitDiagnostics() {
633 SortDiagBySourceLocation SortDiagBySL(S);
634 sort(Warnings.begin(), Warnings.end(), SortDiagBySL);
635 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
636 I != E; ++I)
637 S.Diag(I->first, I->second);
638 }
639
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000640 void handleInvalidLockExp(SourceLocation Loc) {
641 PartialDiagnostic Warning = S.PDiag(diag::warn_cannot_resolve_lock) << Loc;
642 Warnings.push_back(DelayedDiag(Loc, Warning));
643 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000644 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
645 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
646 }
647
648 void handleDoubleLock(Name LockName, SourceLocation Loc) {
649 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
650 }
651
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000652 void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc,
653 LockErrorKind LEK){
654 unsigned DiagID = 0;
655 switch (LEK) {
656 case LEK_LockedSomePredecessors:
657 DiagID = diag::warn_lock_at_end_of_scope;
658 break;
659 case LEK_LockedSomeLoopIterations:
660 DiagID = diag::warn_expecting_lock_held_on_loop;
661 break;
662 case LEK_LockedAtEndOfFunction:
663 DiagID = diag::warn_no_unlock;
664 break;
665 }
666 warnLockMismatch(DiagID, LockName, Loc);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000667 }
668
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000669
670 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
671 SourceLocation Loc2) {
672 PartialDiagnostic Warning =
673 S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName;
674 PartialDiagnostic Note =
675 S.PDiag(diag::note_lock_exclusive_and_shared) << LockName;
676 Warnings.push_back(DelayedDiag(Loc1, Warning));
677 Warnings.push_back(DelayedDiag(Loc2, Note));
678 }
679
680 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
681 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +0000682 assert((POK == POK_VarAccess || POK == POK_VarDereference)
683 && "Only works for variables");
684 unsigned DiagID = POK == POK_VarAccess?
685 diag::warn_variable_requires_any_lock:
686 diag::warn_var_deref_requires_any_lock;
687 PartialDiagnostic Warning = S.PDiag(DiagID)
688 << D->getName() << getLockKindFromAccessKind(AK);
689 Warnings.push_back(DelayedDiag(Loc, Warning));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000690 }
691
692 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
693 Name LockName, LockKind LK, SourceLocation Loc) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +0000694 unsigned DiagID = 0;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000695 switch (POK) {
696 case POK_VarAccess:
697 DiagID = diag::warn_variable_requires_lock;
698 break;
699 case POK_VarDereference:
700 DiagID = diag::warn_var_deref_requires_lock;
701 break;
702 case POK_FunctionCall:
703 DiagID = diag::warn_fun_requires_lock;
704 break;
705 }
706 PartialDiagnostic Warning = S.PDiag(DiagID)
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +0000707 << D->getName() << LockName << LK;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000708 Warnings.push_back(DelayedDiag(Loc, Warning));
709 }
710
711 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
712 PartialDiagnostic Warning =
713 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName;
714 Warnings.push_back(DelayedDiag(Loc, Warning));
715 }
716};
717}
718}
719
Ted Kremenek610068c2011-01-15 02:58:47 +0000720//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000721// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
722// warnings on a function, method, or block.
723//===----------------------------------------------------------------------===//
724
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000725clang::sema::AnalysisBasedWarnings::Policy::Policy() {
726 enableCheckFallThrough = 1;
727 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000728 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000729}
730
Chandler Carruth5d989942011-07-06 16:21:37 +0000731clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
732 : S(s),
733 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000734 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +0000735 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +0000736 MaxCFGBlocksPerFunction(0),
737 NumUninitAnalysisFunctions(0),
738 NumUninitAnalysisVariables(0),
739 MaxUninitAnalysisVariablesPerFunction(0),
740 NumUninitAnalysisBlockVisits(0),
741 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +0000742 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000743 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000744 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +0000745 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000746 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
747 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +0000748 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000749
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000750}
751
Ted Kremenek351ba912011-02-23 01:52:04 +0000752static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000753 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +0000754 i = fscope->PossiblyUnreachableDiags.begin(),
755 e = fscope->PossiblyUnreachableDiags.end();
756 i != e; ++i) {
757 const sema::PossiblyUnreachableDiag &D = *i;
758 S.Diag(D.Loc, D.PD);
759 }
760}
761
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000762void clang::sema::
763AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +0000764 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000765 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +0000766
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000767 // We avoid doing analysis-based warnings when there are errors for
768 // two reasons:
769 // (1) The CFGs often can't be constructed (if the body is invalid), so
770 // don't bother trying.
771 // (2) The code already has problems; running the analysis just takes more
772 // time.
David Blaikied6471f72011-09-25 23:23:43 +0000773 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +0000774
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000775 // Do not do any analysis for declarations in system headers if we are
776 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +0000777 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000778 S.SourceMgr.isInSystemHeader(D->getLocation()))
779 return;
780
John McCalle0054f62010-08-25 05:56:39 +0000781 // For code in dependent contexts, we'll do this at instantiation time.
782 if (cast<DeclContext>(D)->isDependentContext())
783 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000784
Ted Kremenek351ba912011-02-23 01:52:04 +0000785 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
786 // Flush out any possibly unreachable diagnostics.
787 flushDiagnostics(S, fscope);
788 return;
789 }
790
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000791 const Stmt *Body = D->getBody();
792 assert(Body);
793
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000794 AnalysisContext AC(D, 0);
795
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000796 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
797 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000798 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
799 AC.getCFGBuildOptions().AddEHEdges = false;
800 AC.getCFGBuildOptions().AddInitializers = true;
801 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +0000802
803 // Force that certain expressions appear as CFGElements in the CFG. This
804 // is used to speed up various analyses.
805 // FIXME: This isn't the right factoring. This is here for initial
806 // prototyping, but we need a way for analyses to say what expressions they
807 // expect to always be CFGElements and then fill in the BuildOptions
808 // appropriately. This is essentially a layering violation.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000809 if (P.enableCheckUnreachable) {
810 // Unreachable code analysis requires a linearized CFG.
811 AC.getCFGBuildOptions().setAllAlwaysAdd();
812 }
813 else {
814 AC.getCFGBuildOptions()
815 .setAlwaysAdd(Stmt::BinaryOperatorClass)
816 .setAlwaysAdd(Stmt::BlockExprClass)
817 .setAlwaysAdd(Stmt::CStyleCastExprClass)
818 .setAlwaysAdd(Stmt::DeclRefExprClass)
819 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
820 .setAlwaysAdd(Stmt::UnaryOperatorClass);
821 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000822
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +0000823 // Construct the analysis context with the specified CFG build options.
824
Ted Kremenek351ba912011-02-23 01:52:04 +0000825 // Emit delayed diagnostics.
826 if (!fscope->PossiblyUnreachableDiags.empty()) {
827 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +0000828
829 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000830 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000831 i = fscope->PossiblyUnreachableDiags.begin(),
832 e = fscope->PossiblyUnreachableDiags.end();
833 i != e; ++i) {
834 if (const Stmt *stmt = i->stmt)
835 AC.registerForcedBlockExpression(stmt);
836 }
837
838 if (AC.getCFG()) {
839 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000840 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +0000841 i = fscope->PossiblyUnreachableDiags.begin(),
842 e = fscope->PossiblyUnreachableDiags.end();
843 i != e; ++i)
844 {
845 const sema::PossiblyUnreachableDiag &D = *i;
846 bool processed = false;
847 if (const Stmt *stmt = i->stmt) {
848 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
849 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +0000850 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +0000851 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +0000852 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +0000853 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +0000854 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +0000855 }
856 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000857 if (!processed) {
858 // Emit the warning anyway if we cannot map to a basic block.
859 S.Diag(D.Loc, D.PD);
860 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000861 }
Ted Kremenek0d28d362011-03-10 03:50:34 +0000862 }
Ted Kremenek351ba912011-02-23 01:52:04 +0000863
864 if (!analyzed)
865 flushDiagnostics(S, fscope);
866 }
867
868
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000869 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000870 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000871 const CheckFallThroughDiagnostics &CD =
872 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000873 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000874 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000875 }
876
877 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +0000878 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000879 CheckUnreachable(S, AC);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000880
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000881 // Check for thread safety violations
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000882 if (P.enableThreadSafetyAnalysis) {
883 thread_safety::ThreadSafetyReporter Reporter(S);
884 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
885 Reporter.emitDiagnostics();
886 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000887
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000888 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +0000889 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +0000890 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +0000891 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +0000892 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +0000893 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +0000894 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +0000895 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +0000896 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +0000897 reporter, stats);
898
899 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
900 ++NumUninitAnalysisFunctions;
901 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
902 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
903 MaxUninitAnalysisVariablesPerFunction =
904 std::max(MaxUninitAnalysisVariablesPerFunction,
905 stats.NumVariablesAnalyzed);
906 MaxUninitAnalysisBlockVisitsPerFunction =
907 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
908 stats.NumBlockVisits);
909 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000910 }
911 }
Chandler Carruth5d989942011-07-06 16:21:37 +0000912
913 // Collect statistics about the CFG if it was built.
914 if (S.CollectStats && AC.isCFGBuilt()) {
915 ++NumFunctionsAnalyzed;
916 if (CFG *cfg = AC.getCFG()) {
917 // If we successfully built a CFG for this context, record some more
918 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000919 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +0000920 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +0000921 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +0000922 } else {
923 ++NumFunctionsWithBadCFGs;
924 }
925 }
926}
927
928void clang::sema::AnalysisBasedWarnings::PrintStats() const {
929 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
930
931 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
932 unsigned AvgCFGBlocksPerFunction =
933 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
934 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
935 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
936 << " " << NumCFGBlocks << " CFG blocks built.\n"
937 << " " << AvgCFGBlocksPerFunction
938 << " average CFG blocks per function.\n"
939 << " " << MaxCFGBlocksPerFunction
940 << " max CFG blocks per function.\n";
941
942 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
943 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
944 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
945 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
946 llvm::errs() << NumUninitAnalysisFunctions
947 << " functions analyzed for uninitialiazed variables\n"
948 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
949 << " " << AvgUninitVariablesPerFunction
950 << " average variables per function.\n"
951 << " " << MaxUninitAnalysisVariablesPerFunction
952 << " max variables per function.\n"
953 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
954 << " " << AvgUninitBlockVisitsPerFunction
955 << " average block visits per function.\n"
956 << " " << MaxUninitAnalysisBlockVisitsPerFunction
957 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000958}