blob: 8f16e70b154a1a4920d506a05938e04453a4f958 [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"
Richard Smithbdb97ff2012-05-26 06:20:46 +000022#include "clang/Lex/Lexer.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000025#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/StmtObjC.h"
28#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000030#include "clang/AST/StmtVisitor.h"
Richard Smithe0d3b4c2012-05-03 18:27:39 +000031#include "clang/AST/RecursiveASTVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
34#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000035#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000036#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000037#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000038#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000039#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000040#include "llvm/ADT/FoldingSet.h"
41#include "llvm/ADT/ImmutableMap.h"
42#include "llvm/ADT/PostOrderIterator.h"
43#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000044#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000045#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000046#include <algorithm>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000047#include <iterator>
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000048#include <vector>
Richard Smithe0d3b4c2012-05-03 18:27:39 +000049#include <deque>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000050
51using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Unreachable code analysis.
55//===----------------------------------------------------------------------===//
56
57namespace {
58 class UnreachableCodeHandler : public reachable_code::Callback {
59 Sema &S;
60 public:
61 UnreachableCodeHandler(Sema &s) : S(s) {}
62
63 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
64 S.Diag(L, diag::warn_unreachable) << R1 << R2;
65 }
66 };
67}
68
69/// CheckUnreachable - Check for unreachable code.
Ted Kremenek1d26f482011-10-24 01:32:45 +000070static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000071 UnreachableCodeHandler UC(S);
72 reachable_code::FindUnreachableCode(AC, UC);
73}
74
75//===----------------------------------------------------------------------===//
76// Check for missing return value.
77//===----------------------------------------------------------------------===//
78
John McCall16565aa2010-05-16 09:34:11 +000079enum ControlFlowKind {
80 UnknownFallThrough,
81 NeverFallThrough,
82 MaybeFallThrough,
83 AlwaysFallThrough,
84 NeverFallThroughOrReturn
85};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000086
87/// CheckFallThrough - Check that we don't fall off the end of a
88/// Statement that should return a value.
89///
90/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
91/// MaybeFallThrough iff we might or might not fall off the end,
92/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
93/// return. We assume NeverFallThrough iff we never fall off the end of the
94/// statement but we may return. We assume that functions not marked noreturn
95/// will return.
Ted Kremenek1d26f482011-10-24 01:32:45 +000096static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000097 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000098 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000099
100 // The CFG leaves in dead things, and we don't want the dead code paths to
101 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000102 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000103 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000104 live);
105
106 bool AddEHEdges = AC.getAddEHEdges();
107 if (!AddEHEdges && count != cfg->getNumBlockIDs())
108 // When there are things remaining dead, and we didn't add EH edges
109 // from CallExprs to the catch clauses, we have to go back and
110 // mark them as live.
111 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
112 CFGBlock &b = **I;
113 if (!live[b.getBlockID()]) {
114 if (b.pred_begin() == b.pred_end()) {
115 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
116 // When not adding EH edges from calls, catch clauses
117 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000118 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000119 continue;
120 }
121 }
122 }
123
124 // Now we know what is live, we check the live precessors of the exit block
125 // and look for fall through paths, being careful to ignore normal returns,
126 // and exceptional paths.
127 bool HasLiveReturn = false;
128 bool HasFakeEdge = false;
129 bool HasPlainEdge = false;
130 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000131
132 // Ignore default cases that aren't likely to be reachable because all
133 // enums in a switch(X) have explicit case statements.
134 CFGBlock::FilterOptions FO;
135 FO.IgnoreDefaultsWithCoveredEnums = 1;
136
137 for (CFGBlock::filtered_pred_iterator
138 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
139 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000140 if (!live[B.getBlockID()])
141 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000142
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000143 // Skip blocks which contain an element marked as no-return. They don't
144 // represent actually viable edges into the exit block, so mark them as
145 // abnormal.
146 if (B.hasNoReturnElement()) {
147 HasAbnormalEdge = true;
148 continue;
149 }
150
Ted Kremenek5811f592011-01-26 04:49:52 +0000151 // Destructors can appear after the 'return' in the CFG. This is
152 // normal. We need to look pass the destructors for the return
153 // statement (if it exists).
154 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000155
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000156 for ( ; ri != re ; ++ri)
157 if (isa<CFGStmt>(*ri))
Ted Kremenek5811f592011-01-26 04:49:52 +0000158 break;
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000159
Ted Kremenek5811f592011-01-26 04:49:52 +0000160 // No more CFGElements in the block?
161 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000162 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
163 HasAbnormalEdge = true;
164 continue;
165 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000166 // A labeled empty statement, or the entry block...
167 HasPlainEdge = true;
168 continue;
169 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000170
Ted Kremenek5811f592011-01-26 04:49:52 +0000171 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000172 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000173 if (isa<ReturnStmt>(S)) {
174 HasLiveReturn = true;
175 continue;
176 }
177 if (isa<ObjCAtThrowStmt>(S)) {
178 HasFakeEdge = true;
179 continue;
180 }
181 if (isa<CXXThrowExpr>(S)) {
182 HasFakeEdge = true;
183 continue;
184 }
185 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
186 if (AS->isMSAsm()) {
187 HasFakeEdge = true;
188 HasLiveReturn = true;
189 continue;
190 }
191 }
192 if (isa<CXXTryStmt>(S)) {
193 HasAbnormalEdge = true;
194 continue;
195 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000196 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
197 == B.succ_end()) {
198 HasAbnormalEdge = true;
199 continue;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000200 }
Chandler Carruthe05ee6d2011-09-13 09:53:58 +0000201
202 HasPlainEdge = true;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000203 }
204 if (!HasPlainEdge) {
205 if (HasLiveReturn)
206 return NeverFallThrough;
207 return NeverFallThroughOrReturn;
208 }
209 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
210 return MaybeFallThrough;
211 // This says AlwaysFallThrough for calls to functions that are not marked
212 // noreturn, that don't return. If people would like this warning to be more
213 // accurate, such functions should be marked as noreturn.
214 return AlwaysFallThrough;
215}
216
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000217namespace {
218
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000219struct CheckFallThroughDiagnostics {
220 unsigned diag_MaybeFallThrough_HasNoReturn;
221 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
222 unsigned diag_AlwaysFallThrough_HasNoReturn;
223 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
224 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000225 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000226 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000227
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000228 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000229 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000230 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000231 D.diag_MaybeFallThrough_HasNoReturn =
232 diag::warn_falloff_noreturn_function;
233 D.diag_MaybeFallThrough_ReturnsNonVoid =
234 diag::warn_maybe_falloff_nonvoid_function;
235 D.diag_AlwaysFallThrough_HasNoReturn =
236 diag::warn_falloff_noreturn_function;
237 D.diag_AlwaysFallThrough_ReturnsNonVoid =
238 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000239
240 // Don't suggest that virtual functions be marked "noreturn", since they
241 // might be overridden by non-noreturn functions.
242 bool isVirtualMethod = false;
243 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
244 isVirtualMethod = Method->isVirtual();
245
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000246 // Don't suggest that template instantiations be marked "noreturn"
247 bool isTemplateInstantiation = false;
Ted Kremenek75df4ee2011-12-01 00:59:17 +0000248 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
249 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregorfcdd2cb2011-10-10 18:15:57 +0000250
251 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000252 D.diag_NeverFallThroughOrReturn =
253 diag::warn_suggest_noreturn_function;
254 else
255 D.diag_NeverFallThroughOrReturn = 0;
256
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000257 D.funMode = Function;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000258 return D;
259 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000260
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000261 static CheckFallThroughDiagnostics MakeForBlock() {
262 CheckFallThroughDiagnostics D;
263 D.diag_MaybeFallThrough_HasNoReturn =
264 diag::err_noreturn_block_has_return_expr;
265 D.diag_MaybeFallThrough_ReturnsNonVoid =
266 diag::err_maybe_falloff_nonvoid_block;
267 D.diag_AlwaysFallThrough_HasNoReturn =
268 diag::err_noreturn_block_has_return_expr;
269 D.diag_AlwaysFallThrough_ReturnsNonVoid =
270 diag::err_falloff_nonvoid_block;
271 D.diag_NeverFallThroughOrReturn =
272 diag::warn_suggest_noreturn_block;
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000273 D.funMode = Block;
274 return D;
275 }
276
277 static CheckFallThroughDiagnostics MakeForLambda() {
278 CheckFallThroughDiagnostics D;
279 D.diag_MaybeFallThrough_HasNoReturn =
280 diag::err_noreturn_lambda_has_return_expr;
281 D.diag_MaybeFallThrough_ReturnsNonVoid =
282 diag::warn_maybe_falloff_nonvoid_lambda;
283 D.diag_AlwaysFallThrough_HasNoReturn =
284 diag::err_noreturn_lambda_has_return_expr;
285 D.diag_AlwaysFallThrough_ReturnsNonVoid =
286 diag::warn_falloff_nonvoid_lambda;
287 D.diag_NeverFallThroughOrReturn = 0;
288 D.funMode = Lambda;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000289 return D;
290 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000291
David Blaikied6471f72011-09-25 23:23:43 +0000292 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000293 bool HasNoReturn) const {
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000294 if (funMode == Function) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000295 return (ReturnsVoid ||
296 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikied6471f72011-09-25 23:23:43 +0000297 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000298 && (!HasNoReturn ||
299 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikied6471f72011-09-25 23:23:43 +0000300 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000301 && (!ReturnsVoid ||
302 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000303 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000304 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000305
Douglas Gregor793cd1c2012-02-15 16:20:15 +0000306 // For blocks / lambdas.
307 return ReturnsVoid && !HasNoReturn
308 && ((funMode == Lambda) ||
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000309 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikied6471f72011-09-25 23:23:43 +0000310 == DiagnosticsEngine::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000311 }
312};
313
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000314}
315
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000316/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
317/// function that should return a value. Check that we don't fall off the end
318/// of a noreturn function. We assume that functions and blocks not marked
319/// noreturn will return.
320static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000321 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000322 const CheckFallThroughDiagnostics& CD,
Ted Kremenek1d26f482011-10-24 01:32:45 +0000323 AnalysisDeclContext &AC) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000324
325 bool ReturnsVoid = false;
326 bool HasNoReturn = false;
327
328 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
329 ReturnsVoid = FD->getResultType()->isVoidType();
330 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000331 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000332 }
333 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
334 ReturnsVoid = MD->getResultType()->isVoidType();
335 HasNoReturn = MD->hasAttr<NoReturnAttr>();
336 }
337 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000338 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000339 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000340 BlockTy->getPointeeType()->getAs<FunctionType>()) {
341 if (FT->getResultType()->isVoidType())
342 ReturnsVoid = true;
343 if (FT->getNoReturnAttr())
344 HasNoReturn = true;
345 }
346 }
347
David Blaikied6471f72011-09-25 23:23:43 +0000348 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000349
350 // Short circuit for compilation speed.
351 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
352 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000353
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000354 // FIXME: Function try block
355 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
356 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000357 case UnknownFallThrough:
358 break;
359
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000360 case MaybeFallThrough:
361 if (HasNoReturn)
362 S.Diag(Compound->getRBracLoc(),
363 CD.diag_MaybeFallThrough_HasNoReturn);
364 else if (!ReturnsVoid)
365 S.Diag(Compound->getRBracLoc(),
366 CD.diag_MaybeFallThrough_ReturnsNonVoid);
367 break;
368 case AlwaysFallThrough:
369 if (HasNoReturn)
370 S.Diag(Compound->getRBracLoc(),
371 CD.diag_AlwaysFallThrough_HasNoReturn);
372 else if (!ReturnsVoid)
373 S.Diag(Compound->getRBracLoc(),
374 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
375 break;
376 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000377 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
378 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
379 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregorb3321092011-09-10 00:56:20 +0000380 << 0 << FD;
381 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
382 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
383 << 1 << MD;
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000384 } else {
385 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
386 }
387 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000388 break;
389 case NeverFallThrough:
390 break;
391 }
392 }
393}
394
395//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000396// -Wuninitialized
397//===----------------------------------------------------------------------===//
398
Ted Kremenek6f417152011-04-04 20:56:00 +0000399namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000400/// ContainsReference - A visitor class to search for references to
401/// a particular declaration (the needle) within any evaluated component of an
402/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000403class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000404 bool FoundReference;
405 const DeclRefExpr *Needle;
406
Ted Kremenek6f417152011-04-04 20:56:00 +0000407public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000408 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
409 : EvaluatedExprVisitor<ContainsReference>(Context),
410 FoundReference(false), Needle(Needle) {}
411
412 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000413 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000414 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000415 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000416
417 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000418 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000419
420 void VisitDeclRefExpr(DeclRefExpr *E) {
421 if (E == Needle)
422 FoundReference = true;
423 else
424 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000425 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000426
427 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000428};
429}
430
David Blaikie4f4f3492011-09-10 05:35:08 +0000431static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000432 QualType VariableTy = VD->getType().getCanonicalType();
433 if (VariableTy->isBlockPointerType() &&
434 !VD->hasAttr<BlocksAttr>()) {
435 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
436 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
437 return true;
438 }
439
David Blaikie4f4f3492011-09-10 05:35:08 +0000440 // Don't issue a fixit if there is already an initializer.
441 if (VD->getInit())
442 return false;
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000443
David Blaikie4f4f3492011-09-10 05:35:08 +0000444 // Suggest possible initialization (if any).
David Blaikie2c0abf42012-04-30 18:27:22 +0000445 std::string Init = S.getFixItZeroInitializerForType(VariableTy);
446 if (Init.empty())
David Blaikie4f4f3492011-09-10 05:35:08 +0000447 return false;
Richard Trieu7b0a3e32012-05-03 01:09:59 +0000448
449 // Don't suggest a fixit inside macros.
450 if (VD->getLocEnd().isMacroID())
451 return false;
452
Richard Smith7984de32012-01-12 23:53:29 +0000453 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000454
Richard Smith7984de32012-01-12 23:53:29 +0000455 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
456 << FixItHint::CreateInsertion(Loc, Init);
457 return true;
David Blaikie4f4f3492011-09-10 05:35:08 +0000458}
459
Richard Smithbdb97ff2012-05-26 06:20:46 +0000460/// Create a fixit to remove an if-like statement, on the assumption that its
461/// condition is CondVal.
462static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
463 const Stmt *Else, bool CondVal,
464 FixItHint &Fixit1, FixItHint &Fixit2) {
465 if (CondVal) {
466 // If condition is always true, remove all but the 'then'.
467 Fixit1 = FixItHint::CreateRemoval(
468 CharSourceRange::getCharRange(If->getLocStart(),
469 Then->getLocStart()));
470 if (Else) {
471 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
472 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
473 Fixit2 = FixItHint::CreateRemoval(
474 SourceRange(ElseKwLoc, Else->getLocEnd()));
475 }
476 } else {
477 // If condition is always false, remove all but the 'else'.
478 if (Else)
479 Fixit1 = FixItHint::CreateRemoval(
480 CharSourceRange::getCharRange(If->getLocStart(),
481 Else->getLocStart()));
482 else
483 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
484 }
485}
486
487/// DiagUninitUse -- Helper function to produce a diagnostic for an
488/// uninitialized use of a variable.
489static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
490 bool IsCapturedByBlock) {
491 bool Diagnosed = false;
492
493 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith2815e1a2012-05-25 02:17:09 +0000494 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
495 I != E; ++I) {
Richard Smithbdb97ff2012-05-26 06:20:46 +0000496 assert(Use.getKind() == UninitUse::Sometimes);
497
498 const Expr *User = Use.getUser();
Richard Smith2815e1a2012-05-25 02:17:09 +0000499 const Stmt *Term = I->Terminator;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000500
501 // Information used when building the diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000502 unsigned DiagKind;
Richard Smith2815e1a2012-05-25 02:17:09 +0000503 const char *Str;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000504 SourceRange Range;
505
506 // FixIts to suppress the diagnosic by removing the dead condition.
507 // For all binary terminators, branch 0 is taken if the condition is true,
508 // and branch 1 is taken if the condition is false.
509 int RemoveDiagKind = -1;
510 const char *FixitStr =
511 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
512 : (I->Output ? "1" : "0");
513 FixItHint Fixit1, Fixit2;
514
Richard Smith2815e1a2012-05-25 02:17:09 +0000515 switch (Term->getStmtClass()) {
516 default:
Richard Smithbdb97ff2012-05-26 06:20:46 +0000517 // Don't know how to report this. Just fall back to 'may be used
518 // uninitialized'. This happens for range-based for, which the user
519 // can't explicitly fix.
520 // FIXME: This also happens if the first use of a variable is always
521 // uninitialized, eg "for (int n; n < 10; ++n)". We should report that
522 // with the 'is uninitialized' diagnostic.
Richard Smith2815e1a2012-05-25 02:17:09 +0000523 continue;
524
525 // "condition is true / condition is false".
Richard Smithbdb97ff2012-05-26 06:20:46 +0000526 case Stmt::IfStmtClass: {
527 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000528 DiagKind = 0;
529 Str = "if";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000530 Range = IS->getCond()->getSourceRange();
531 RemoveDiagKind = 0;
532 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
533 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000534 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000535 }
536 case Stmt::ConditionalOperatorClass: {
537 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith2815e1a2012-05-25 02:17:09 +0000538 DiagKind = 0;
539 Str = "?:";
Richard Smithbdb97ff2012-05-26 06:20:46 +0000540 Range = CO->getCond()->getSourceRange();
541 RemoveDiagKind = 0;
542 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
543 I->Output, Fixit1, Fixit2);
Richard Smith2815e1a2012-05-25 02:17:09 +0000544 break;
Richard Smithbdb97ff2012-05-26 06:20:46 +0000545 }
Richard Smith2815e1a2012-05-25 02:17:09 +0000546 case Stmt::BinaryOperatorClass: {
547 const BinaryOperator *BO = cast<BinaryOperator>(Term);
548 if (!BO->isLogicalOp())
549 continue;
550 DiagKind = 0;
551 Str = BO->getOpcodeStr();
552 Range = BO->getLHS()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000553 RemoveDiagKind = 0;
554 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
555 (BO->getOpcode() == BO_LOr && !I->Output))
556 // true && y -> y, false || y -> y.
557 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
558 BO->getOperatorLoc()));
559 else
560 // false && y -> false, true || y -> true.
561 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000562 break;
563 }
564
565 // "loop is entered / loop is exited".
566 case Stmt::WhileStmtClass:
567 DiagKind = 1;
568 Str = "while";
569 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000570 RemoveDiagKind = 1;
571 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000572 break;
573 case Stmt::ForStmtClass:
574 DiagKind = 1;
575 Str = "for";
576 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000577 RemoveDiagKind = 1;
578 if (I->Output)
579 Fixit1 = FixItHint::CreateRemoval(Range);
580 else
581 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000582 break;
583
584 // "condition is true / loop is exited".
585 case Stmt::DoStmtClass:
586 DiagKind = 2;
587 Str = "do";
588 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000589 RemoveDiagKind = 1;
590 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith2815e1a2012-05-25 02:17:09 +0000591 break;
592
593 // "switch case is taken".
594 case Stmt::CaseStmtClass:
595 DiagKind = 3;
596 Str = "case";
597 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
598 break;
599 case Stmt::DefaultStmtClass:
600 DiagKind = 3;
601 Str = "default";
602 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
603 break;
604 }
605
Richard Smithbdb97ff2012-05-26 06:20:46 +0000606 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
607 << VD->getDeclName() << IsCapturedByBlock << DiagKind
608 << Str << I->Output << Range;
609 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
610 << IsCapturedByBlock << User->getSourceRange();
611 if (RemoveDiagKind != -1)
612 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
613 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
614
615 Diagnosed = true;
Richard Smith2815e1a2012-05-25 02:17:09 +0000616 }
Richard Smithbdb97ff2012-05-26 06:20:46 +0000617
618 if (!Diagnosed)
619 S.Diag(Use.getUser()->getLocStart(),
620 Use.getKind() == UninitUse::Always ? diag::warn_uninit_var
621 : diag::warn_maybe_uninit_var)
622 << VD->getDeclName() << IsCapturedByBlock
623 << Use.getUser()->getSourceRange();
Richard Smith2815e1a2012-05-25 02:17:09 +0000624}
625
Chandler Carruth262d50e2011-04-05 18:27:05 +0000626/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
627/// uninitialized variable. This manages the different forms of diagnostic
628/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith2815e1a2012-05-25 02:17:09 +0000629/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruth262d50e2011-04-05 18:27:05 +0000630/// false.
631static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith2815e1a2012-05-25 02:17:09 +0000632 const UninitUse &Use,
Ted Kremenek9e761722011-10-13 18:50:06 +0000633 bool alwaysReportSelfInit = false) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000634
Richard Smith2815e1a2012-05-25 02:17:09 +0000635 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieuf6278e52012-05-09 21:08:22 +0000636 // Inspect the initializer of the variable declaration which is
637 // being referenced prior to its initialization. We emit
638 // specialized diagnostics for self-initialization, and we
639 // specifically avoid warning about self references which take the
640 // form of:
641 //
642 // int x = x;
643 //
644 // This is used to indicate to GCC that 'x' is intentionally left
645 // uninitialized. Proven code paths which access 'x' in
646 // an uninitialized state after this will still warn.
647 if (const Expr *Initializer = VD->getInit()) {
648 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
649 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000650
Richard Trieuf6278e52012-05-09 21:08:22 +0000651 ContainsReference CR(S.Context, DRE);
652 CR.Visit(const_cast<Expr*>(Initializer));
653 if (CR.doesContainReference()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000654 S.Diag(DRE->getLocStart(),
655 diag::warn_uninit_self_reference_in_init)
Richard Trieuf6278e52012-05-09 21:08:22 +0000656 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
657 return true;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000658 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000659 }
Richard Trieuf6278e52012-05-09 21:08:22 +0000660
Richard Smithbdb97ff2012-05-26 06:20:46 +0000661 DiagUninitUse(S, VD, Use, false);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000662 } else {
Richard Smith2815e1a2012-05-25 02:17:09 +0000663 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smithbdb97ff2012-05-26 06:20:46 +0000664 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
665 S.Diag(BE->getLocStart(),
666 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahaniana34194f2012-03-08 00:22:50 +0000667 << VD->getDeclName();
Richard Smithbdb97ff2012-05-26 06:20:46 +0000668 else
669 DiagUninitUse(S, VD, Use, true);
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000670 }
671
672 // Report where the variable was declared when the use wasn't within
David Blaikie4f4f3492011-09-10 05:35:08 +0000673 // the initializer of that declaration & we didn't already suggest
674 // an initialization fixit.
Richard Trieuf6278e52012-05-09 21:08:22 +0000675 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000676 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
677 << VD->getDeclName();
678
Chandler Carruth262d50e2011-04-05 18:27:05 +0000679 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000680}
681
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000682namespace {
683 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
684 public:
685 FallthroughMapper(Sema &S)
686 : FoundSwitchStatements(false),
687 S(S) {
688 }
689
690 bool foundSwitchStatements() const { return FoundSwitchStatements; }
691
692 void markFallthroughVisited(const AttributedStmt *Stmt) {
693 bool Found = FallthroughStmts.erase(Stmt);
694 assert(Found);
Kaelyn Uhrain3bb29942012-05-03 19:46:38 +0000695 (void)Found;
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000696 }
697
698 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
699
700 const AttrStmts &getFallthroughStmts() const {
701 return FallthroughStmts;
702 }
703
704 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
705 int UnannotatedCnt = 0;
706 AnnotatedCnt = 0;
707
708 std::deque<const CFGBlock*> BlockQueue;
709
710 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
711
712 while (!BlockQueue.empty()) {
713 const CFGBlock *P = BlockQueue.front();
714 BlockQueue.pop_front();
715
716 const Stmt *Term = P->getTerminator();
717 if (Term && isa<SwitchStmt>(Term))
718 continue; // Switch statement, good.
719
720 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
721 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
722 continue; // Previous case label has no statements, good.
723
724 if (P->pred_begin() == P->pred_end()) { // The block is unreachable.
725 // This only catches trivially unreachable blocks.
726 for (CFGBlock::const_iterator ElIt = P->begin(), ElEnd = P->end();
727 ElIt != ElEnd; ++ElIt) {
728 if (const CFGStmt *CS = ElIt->getAs<CFGStmt>()){
729 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
730 S.Diag(AS->getLocStart(),
731 diag::warn_fallthrough_attr_unreachable);
732 markFallthroughVisited(AS);
733 ++AnnotatedCnt;
734 }
735 // Don't care about other unreachable statements.
736 }
737 }
738 // If there are no unreachable statements, this may be a special
739 // case in CFG:
740 // case X: {
741 // A a; // A has a destructor.
742 // break;
743 // }
744 // // <<<< This place is represented by a 'hanging' CFG block.
745 // case Y:
746 continue;
747 }
748
749 const Stmt *LastStmt = getLastStmt(*P);
750 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
751 markFallthroughVisited(AS);
752 ++AnnotatedCnt;
753 continue; // Fallthrough annotation, good.
754 }
755
756 if (!LastStmt) { // This block contains no executable statements.
757 // Traverse its predecessors.
758 std::copy(P->pred_begin(), P->pred_end(),
759 std::back_inserter(BlockQueue));
760 continue;
761 }
762
763 ++UnannotatedCnt;
764 }
765 return !!UnannotatedCnt;
766 }
767
768 // RecursiveASTVisitor setup.
769 bool shouldWalkTypesOfTypeLocs() const { return false; }
770
771 bool VisitAttributedStmt(AttributedStmt *S) {
772 if (asFallThroughAttr(S))
773 FallthroughStmts.insert(S);
774 return true;
775 }
776
777 bool VisitSwitchStmt(SwitchStmt *S) {
778 FoundSwitchStatements = true;
779 return true;
780 }
781
782 private:
783
784 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
785 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
786 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
787 return AS;
788 }
789 return 0;
790 }
791
792 static const Stmt *getLastStmt(const CFGBlock &B) {
793 if (const Stmt *Term = B.getTerminator())
794 return Term;
795 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
796 ElemEnd = B.rend();
797 ElemIt != ElemEnd; ++ElemIt) {
798 if (const CFGStmt *CS = ElemIt->getAs<CFGStmt>())
799 return CS->getStmt();
800 }
801 // Workaround to detect a statement thrown out by CFGBuilder:
802 // case X: {} case Y:
803 // case X: ; case Y:
804 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
805 if (!isa<SwitchCase>(SW->getSubStmt()))
806 return SW->getSubStmt();
807
808 return 0;
809 }
810
811 bool FoundSwitchStatements;
812 AttrStmts FallthroughStmts;
813 Sema &S;
814 };
815}
816
817static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC) {
818 FallthroughMapper FM(S);
819 FM.TraverseStmt(AC.getBody());
820
821 if (!FM.foundSwitchStatements())
822 return;
823
824 CFG *Cfg = AC.getCFG();
825
826 if (!Cfg)
827 return;
828
829 int AnnotatedCnt;
830
831 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
832 const CFGBlock &B = **I;
833 const Stmt *Label = B.getLabel();
834
835 if (!Label || !isa<SwitchCase>(Label))
836 continue;
837
838 if (!FM.checkFallThroughIntoBlock(B, AnnotatedCnt))
839 continue;
840
841 S.Diag(Label->getLocStart(), diag::warn_unannotated_fallthrough);
842
843 if (!AnnotatedCnt) {
844 SourceLocation L = Label->getLocStart();
845 if (L.isMacroID())
846 continue;
847 if (S.getLangOpts().CPlusPlus0x) {
Alexander Kornienkoa189d892012-05-26 00:49:15 +0000848 const Stmt *Term = B.getTerminator();
849 if (!(B.empty() && Term && isa<BreakStmt>(Term))) {
850 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
851 FixItHint::CreateInsertion(L, "[[clang::fallthrough]]; ");
852 }
Richard Smithe0d3b4c2012-05-03 18:27:39 +0000853 }
854 S.Diag(L, diag::note_insert_break_fixit) <<
855 FixItHint::CreateInsertion(L, "break; ");
856 }
857 }
858
859 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
860 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
861 E = Fallthroughs.end();
862 I != E; ++I) {
863 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
864 }
865
866}
867
Ted Kremenek610068c2011-01-15 02:58:47 +0000868namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000869struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000870 bool operator()(const UninitUse &a, const UninitUse &b) {
Richard Smith2815e1a2012-05-25 02:17:09 +0000871 // Prefer a more confident report over a less confident one.
872 if (a.getKind() != b.getKind())
873 return a.getKind() > b.getKind();
874 SourceLocation aLoc = a.getUser()->getLocStart();
875 SourceLocation bLoc = b.getUser()->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000876 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
877 }
878};
879
Ted Kremenek610068c2011-01-15 02:58:47 +0000880class UninitValsDiagReporter : public UninitVariablesHandler {
881 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000882 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek9e761722011-10-13 18:50:06 +0000883 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000884 UsesMap *uses;
885
Ted Kremenek610068c2011-01-15 02:58:47 +0000886public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000887 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
888 ~UninitValsDiagReporter() {
889 flushDiagnostics();
890 }
Ted Kremenek9e761722011-10-13 18:50:06 +0000891
892 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000893 if (!uses)
894 uses = new UsesMap();
Ted Kremenek9e761722011-10-13 18:50:06 +0000895
896 UsesMap::mapped_type &V = (*uses)[vd];
897 UsesVec *&vec = V.first;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000898 if (!vec)
899 vec = new UsesVec();
900
Ted Kremenek9e761722011-10-13 18:50:06 +0000901 return V;
902 }
903
Richard Smith2815e1a2012-05-25 02:17:09 +0000904 void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
905 getUses(vd).first->push_back(use);
Ted Kremenek9e761722011-10-13 18:50:06 +0000906 }
907
908 void handleSelfInit(const VarDecl *vd) {
909 getUses(vd).second = true;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000910 }
911
912 void flushDiagnostics() {
913 if (!uses)
914 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000915
Richard Smith81891882012-05-24 23:45:35 +0000916 // FIXME: This iteration order, and thus the resulting diagnostic order,
917 // is nondeterministic.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000918 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
919 const VarDecl *vd = i->first;
Ted Kremenek9e761722011-10-13 18:50:06 +0000920 const UsesMap::mapped_type &V = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000921
Ted Kremenek9e761722011-10-13 18:50:06 +0000922 UsesVec *vec = V.first;
923 bool hasSelfInit = V.second;
924
925 // Specially handle the case where we have uses of an uninitialized
926 // variable, but the root cause is an idiomatic self-init. We want
927 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000928 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith2815e1a2012-05-25 02:17:09 +0000929 DiagnoseUninitializedUse(S, vd,
930 UninitUse(vd->getInit()->IgnoreParenCasts(),
931 /* isAlwaysUninit */ true),
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000932 /* alwaysReportSelfInit */ true);
Ted Kremenek9e761722011-10-13 18:50:06 +0000933 else {
934 // Sort the uses by their SourceLocations. While not strictly
935 // guaranteed to produce them in line/column order, this will provide
936 // a stable ordering.
937 std::sort(vec->begin(), vec->end(), SLocSort());
938
939 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
940 ++vi) {
Richard Smith2815e1a2012-05-25 02:17:09 +0000941 // If we have self-init, downgrade all uses to 'may be uninitialized'.
942 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
943
944 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek9e761722011-10-13 18:50:06 +0000945 // Skip further diagnostics for this variable. We try to warn only
946 // on the first point at which a variable is used uninitialized.
947 break;
948 }
Chandler Carruth64fb9592011-04-05 18:18:08 +0000949 }
Ted Kremenek9e761722011-10-13 18:50:06 +0000950
951 // Release the uses vector.
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000952 delete vec;
953 }
954 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000955 }
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000956
957private:
958 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
959 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smith2815e1a2012-05-25 02:17:09 +0000960 if (i->getKind() == UninitUse::Always) {
Matt Beaumont-Gay0d381812011-10-19 18:53:03 +0000961 return true;
962 }
963 }
964 return false;
965}
Ted Kremenek610068c2011-01-15 02:58:47 +0000966};
967}
968
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000969
970//===----------------------------------------------------------------------===//
971// -Wthread-safety
972//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000973namespace clang {
974namespace thread_safety {
Richard Smith2e515622012-02-03 04:45:26 +0000975typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
976typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramerecafd302012-03-26 14:05:40 +0000977typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000978
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000979struct SortDiagBySourceLocation {
Benjamin Kramerecafd302012-03-26 14:05:40 +0000980 SourceManager &SM;
981 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000982
983 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
984 // Although this call will be slow, this is only called when outputting
985 // multiple warnings.
Benjamin Kramerecafd302012-03-26 14:05:40 +0000986 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000987 }
988};
989
David Blaikie99ba9e32011-12-20 02:48:34 +0000990namespace {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000991class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
992 Sema &S;
993 DiagList Warnings;
Richard Smith2e515622012-02-03 04:45:26 +0000994 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000995
996 // Helper functions
997 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000998 // Gracefully handle rare cases when the analysis can't get a more
999 // precise source location.
1000 if (!Loc.isValid())
1001 Loc = FunLocation;
Richard Smith2e515622012-02-03 04:45:26 +00001002 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1003 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001004 }
1005
1006 public:
Richard Smith2e515622012-02-03 04:45:26 +00001007 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1008 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001009
1010 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1011 /// We need to output diagnostics produced while iterating through
1012 /// the lockset in deterministic order, so this function orders diagnostics
1013 /// and outputs them.
1014 void emitDiagnostics() {
Benjamin Kramerecafd302012-03-26 14:05:40 +00001015 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001016 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith2e515622012-02-03 04:45:26 +00001017 I != E; ++I) {
1018 S.Diag(I->first.first, I->first.second);
1019 const OptionalNotes &Notes = I->second;
1020 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1021 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1022 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001023 }
1024
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001025 void handleInvalidLockExp(SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001026 PartialDiagnosticAt Warning(Loc,
1027 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1028 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski99107eb2011-09-09 16:21:55 +00001029 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001030 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1031 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1032 }
1033
1034 void handleDoubleLock(Name LockName, SourceLocation Loc) {
1035 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1036 }
1037
Richard Smith2e515622012-02-03 04:45:26 +00001038 void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1039 SourceLocation LocEndOfScope,
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001040 LockErrorKind LEK){
1041 unsigned DiagID = 0;
1042 switch (LEK) {
1043 case LEK_LockedSomePredecessors:
Richard Smith2e515622012-02-03 04:45:26 +00001044 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001045 break;
1046 case LEK_LockedSomeLoopIterations:
1047 DiagID = diag::warn_expecting_lock_held_on_loop;
1048 break;
1049 case LEK_LockedAtEndOfFunction:
1050 DiagID = diag::warn_no_unlock;
1051 break;
1052 }
Richard Smith2e515622012-02-03 04:45:26 +00001053 if (LocEndOfScope.isInvalid())
1054 LocEndOfScope = FunEndLocation;
1055
1056 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
1057 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1058 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001059 }
1060
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001061
1062 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1063 SourceLocation Loc2) {
Richard Smith2e515622012-02-03 04:45:26 +00001064 PartialDiagnosticAt Warning(
1065 Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1066 PartialDiagnosticAt Note(
1067 Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1068 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001069 }
1070
1071 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1072 AccessKind AK, SourceLocation Loc) {
Caitlin Sadowskidf8327c2011-09-14 20:09:09 +00001073 assert((POK == POK_VarAccess || POK == POK_VarDereference)
1074 && "Only works for variables");
1075 unsigned DiagID = POK == POK_VarAccess?
1076 diag::warn_variable_requires_any_lock:
1077 diag::warn_var_deref_requires_any_lock;
Richard Smith2e515622012-02-03 04:45:26 +00001078 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1079 << D->getName() << getLockKindFromAccessKind(AK));
1080 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001081 }
1082
1083 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
1084 Name LockName, LockKind LK, SourceLocation Loc) {
Caitlin Sadowskie87158d2011-09-13 18:01:58 +00001085 unsigned DiagID = 0;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001086 switch (POK) {
1087 case POK_VarAccess:
1088 DiagID = diag::warn_variable_requires_lock;
1089 break;
1090 case POK_VarDereference:
1091 DiagID = diag::warn_var_deref_requires_lock;
1092 break;
1093 case POK_FunctionCall:
1094 DiagID = diag::warn_fun_requires_lock;
1095 break;
1096 }
Richard Smith2e515622012-02-03 04:45:26 +00001097 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1098 << D->getName() << LockName << LK);
1099 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001100 }
1101
1102 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
Richard Smith2e515622012-02-03 04:45:26 +00001103 PartialDiagnosticAt Warning(Loc,
1104 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1105 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001106 }
1107};
1108}
1109}
David Blaikie99ba9e32011-12-20 02:48:34 +00001110}
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001111
Ted Kremenek610068c2011-01-15 02:58:47 +00001112//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001113// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1114// warnings on a function, method, or block.
1115//===----------------------------------------------------------------------===//
1116
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001117clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1118 enableCheckFallThrough = 1;
1119 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001120 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001121}
1122
Chandler Carruth5d989942011-07-06 16:21:37 +00001123clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1124 : S(s),
1125 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001126 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001127 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001128 MaxCFGBlocksPerFunction(0),
1129 NumUninitAnalysisFunctions(0),
1130 NumUninitAnalysisVariables(0),
1131 MaxUninitAnalysisVariablesPerFunction(0),
1132 NumUninitAnalysisBlockVisits(0),
1133 MaxUninitAnalysisBlockVisitsPerFunction(0) {
David Blaikied6471f72011-09-25 23:23:43 +00001134 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001135 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001136 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001137 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001138 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1139 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
David Blaikied6471f72011-09-25 23:23:43 +00001140 DiagnosticsEngine::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001141
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001142}
1143
Ted Kremenek351ba912011-02-23 01:52:04 +00001144static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001145 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001146 i = fscope->PossiblyUnreachableDiags.begin(),
1147 e = fscope->PossiblyUnreachableDiags.end();
1148 i != e; ++i) {
1149 const sema::PossiblyUnreachableDiag &D = *i;
1150 S.Diag(D.Loc, D.PD);
1151 }
1152}
1153
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001154void clang::sema::
1155AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001156 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001157 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001158
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001159 // We avoid doing analysis-based warnings when there are errors for
1160 // two reasons:
1161 // (1) The CFGs often can't be constructed (if the body is invalid), so
1162 // don't bother trying.
1163 // (2) The code already has problems; running the analysis just takes more
1164 // time.
David Blaikied6471f72011-09-25 23:23:43 +00001165 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek99e81922010-04-30 21:49:25 +00001166
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001167 // Do not do any analysis for declarations in system headers if we are
1168 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001169 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001170 S.SourceMgr.isInSystemHeader(D->getLocation()))
1171 return;
1172
John McCalle0054f62010-08-25 05:56:39 +00001173 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie23661d32012-01-24 04:51:48 +00001174 if (cast<DeclContext>(D)->isDependentContext())
1175 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001176
Ted Kremenek351ba912011-02-23 01:52:04 +00001177 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1178 // Flush out any possibly unreachable diagnostics.
1179 flushDiagnostics(S, fscope);
1180 return;
1181 }
1182
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001183 const Stmt *Body = D->getBody();
1184 assert(Body);
1185
Jordy Rosed2001872012-04-28 01:58:08 +00001186 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001187
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001188 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1189 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001190 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1191 AC.getCFGBuildOptions().AddEHEdges = false;
1192 AC.getCFGBuildOptions().AddInitializers = true;
1193 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001194
1195 // Force that certain expressions appear as CFGElements in the CFG. This
1196 // is used to speed up various analyses.
1197 // FIXME: This isn't the right factoring. This is here for initial
1198 // prototyping, but we need a way for analyses to say what expressions they
1199 // expect to always be CFGElements and then fill in the BuildOptions
1200 // appropriately. This is essentially a layering violation.
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001201 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
1202 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001203 AC.getCFGBuildOptions().setAllAlwaysAdd();
1204 }
1205 else {
1206 AC.getCFGBuildOptions()
1207 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1208 .setAlwaysAdd(Stmt::BlockExprClass)
1209 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1210 .setAlwaysAdd(Stmt::DeclRefExprClass)
1211 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001212 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1213 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001214 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001215
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001216 // Construct the analysis context with the specified CFG build options.
1217
Ted Kremenek351ba912011-02-23 01:52:04 +00001218 // Emit delayed diagnostics.
David Blaikie23661d32012-01-24 04:51:48 +00001219 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001220 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001221
1222 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001223 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001224 i = fscope->PossiblyUnreachableDiags.begin(),
1225 e = fscope->PossiblyUnreachableDiags.end();
1226 i != e; ++i) {
1227 if (const Stmt *stmt = i->stmt)
1228 AC.registerForcedBlockExpression(stmt);
1229 }
1230
1231 if (AC.getCFG()) {
1232 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001233 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001234 i = fscope->PossiblyUnreachableDiags.begin(),
1235 e = fscope->PossiblyUnreachableDiags.end();
1236 i != e; ++i)
1237 {
1238 const sema::PossiblyUnreachableDiag &D = *i;
1239 bool processed = false;
1240 if (const Stmt *stmt = i->stmt) {
1241 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedman71b8fb52012-01-21 01:01:51 +00001242 CFGReverseBlockReachabilityAnalysis *cra =
1243 AC.getCFGReachablityAnalysis();
1244 // FIXME: We should be able to assert that block is non-null, but
1245 // the CFG analysis can skip potentially-evaluated expressions in
1246 // edge cases; see test/Sema/vla-2.c.
1247 if (block && cra) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001248 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001249 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001250 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001251 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001252 }
1253 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001254 if (!processed) {
1255 // Emit the warning anyway if we cannot map to a basic block.
1256 S.Diag(D.Loc, D.PD);
1257 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001258 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001259 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001260
1261 if (!analyzed)
1262 flushDiagnostics(S, fscope);
1263 }
1264
1265
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001266 // Warning: check missing 'return'
David Blaikie23661d32012-01-24 04:51:48 +00001267 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001268 const CheckFallThroughDiagnostics &CD =
1269 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregor793cd1c2012-02-15 16:20:15 +00001270 : (isa<CXXMethodDecl>(D) &&
1271 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1272 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1273 ? CheckFallThroughDiagnostics::MakeForLambda()
1274 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001275 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001276 }
1277
1278 // Warning: check for unreachable code
Ted Kremenek5dfee062011-11-30 21:22:09 +00001279 if (P.enableCheckUnreachable) {
1280 // Only check for unreachable code on non-template instantiations.
1281 // Different template instantiations can effectively change the control-flow
1282 // and it is very difficult to prove that a snippet of code in a template
1283 // is unreachable for all instantiations.
Ted Kremenek75df4ee2011-12-01 00:59:17 +00001284 bool isTemplateInstantiation = false;
1285 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1286 isTemplateInstantiation = Function->isTemplateInstantiation();
1287 if (!isTemplateInstantiation)
Ted Kremenek5dfee062011-11-30 21:22:09 +00001288 CheckUnreachable(S, AC);
1289 }
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001290
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001291 // Check for thread safety violations
David Blaikie23661d32012-01-24 04:51:48 +00001292 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001293 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith2e515622012-02-03 04:45:26 +00001294 SourceLocation FEL = AC.getDecl()->getLocEnd();
1295 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001296 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1297 Reporter.emitDiagnostics();
1298 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001299
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001300 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001301 != DiagnosticsEngine::Ignored ||
Richard Smith2815e1a2012-05-25 02:17:09 +00001302 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1303 != DiagnosticsEngine::Ignored ||
Ted Kremenek76709bf2011-03-15 05:22:28 +00001304 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikied6471f72011-09-25 23:23:43 +00001305 != DiagnosticsEngine::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001306 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001307 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001308 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001309 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001310 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001311 reporter, stats);
1312
1313 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1314 ++NumUninitAnalysisFunctions;
1315 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1316 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1317 MaxUninitAnalysisVariablesPerFunction =
1318 std::max(MaxUninitAnalysisVariablesPerFunction,
1319 stats.NumVariablesAnalyzed);
1320 MaxUninitAnalysisBlockVisitsPerFunction =
1321 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1322 stats.NumBlockVisits);
1323 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001324 }
1325 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001326
Richard Smithe0d3b4c2012-05-03 18:27:39 +00001327 if (Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1328 D->getLocStart()) != DiagnosticsEngine::Ignored) {
1329 DiagnoseSwitchLabelsFallthrough(S, AC);
1330 }
1331
Chandler Carruth5d989942011-07-06 16:21:37 +00001332 // Collect statistics about the CFG if it was built.
1333 if (S.CollectStats && AC.isCFGBuilt()) {
1334 ++NumFunctionsAnalyzed;
1335 if (CFG *cfg = AC.getCFG()) {
1336 // If we successfully built a CFG for this context, record some more
1337 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001338 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001339 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001340 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001341 } else {
1342 ++NumFunctionsWithBadCFGs;
1343 }
1344 }
1345}
1346
1347void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1348 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1349
1350 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1351 unsigned AvgCFGBlocksPerFunction =
1352 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1353 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1354 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1355 << " " << NumCFGBlocks << " CFG blocks built.\n"
1356 << " " << AvgCFGBlocksPerFunction
1357 << " average CFG blocks per function.\n"
1358 << " " << MaxCFGBlocksPerFunction
1359 << " max CFG blocks per function.\n";
1360
1361 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1362 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1363 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1364 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1365 llvm::errs() << NumUninitAnalysisFunctions
1366 << " functions analyzed for uninitialiazed variables\n"
1367 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1368 << " " << AvgUninitVariablesPerFunction
1369 << " average variables per function.\n"
1370 << " " << MaxUninitAnalysisVariablesPerFunction
1371 << " max variables per function.\n"
1372 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1373 << " " << AvgUninitBlockVisitsPerFunction
1374 << " average block visits per function.\n"
1375 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1376 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001377}