blob: f3f168a5c1925a83b3c19b52424b20008fb37edb [file] [log] [blame]
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000018#include "clang/Sema/ScopeInfo.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000019#include "clang/Basic/SourceManager.h"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000020#include "clang/Lex/Preprocessor.h"
John McCall7cd088e2010-08-24 07:21:54 +000021#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000023#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000028#include "clang/AST/StmtVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000029#include "clang/Analysis/AnalysisContext.h"
30#include "clang/Analysis/CFG.h"
31#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000032#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
33#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000034#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000035#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000036#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/ImmutableMap.h"
38#include "llvm/ADT/PostOrderIterator.h"
39#include "llvm/ADT/SmallVector.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000040#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000041#include <algorithm>
42#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000043
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47// Unreachable code analysis.
48//===----------------------------------------------------------------------===//
49
50namespace {
51 class UnreachableCodeHandler : public reachable_code::Callback {
52 Sema &S;
53 public:
54 UnreachableCodeHandler(Sema &s) : S(s) {}
55
56 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
57 S.Diag(L, diag::warn_unreachable) << R1 << R2;
58 }
59 };
60}
61
62/// CheckUnreachable - Check for unreachable code.
63static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
64 UnreachableCodeHandler UC(S);
65 reachable_code::FindUnreachableCode(AC, UC);
66}
67
68//===----------------------------------------------------------------------===//
69// Check for missing return value.
70//===----------------------------------------------------------------------===//
71
John McCall16565aa2010-05-16 09:34:11 +000072enum ControlFlowKind {
73 UnknownFallThrough,
74 NeverFallThrough,
75 MaybeFallThrough,
76 AlwaysFallThrough,
77 NeverFallThroughOrReturn
78};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000079
80/// CheckFallThrough - Check that we don't fall off the end of a
81/// Statement that should return a value.
82///
83/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
84/// MaybeFallThrough iff we might or might not fall off the end,
85/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
86/// return. We assume NeverFallThrough iff we never fall off the end of the
87/// statement but we may return. We assume that functions not marked noreturn
88/// will return.
89static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
90 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000091 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000092
93 // The CFG leaves in dead things, and we don't want the dead code paths to
94 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000095 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +000096 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000097 live);
98
99 bool AddEHEdges = AC.getAddEHEdges();
100 if (!AddEHEdges && count != cfg->getNumBlockIDs())
101 // When there are things remaining dead, and we didn't add EH edges
102 // from CallExprs to the catch clauses, we have to go back and
103 // mark them as live.
104 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
105 CFGBlock &b = **I;
106 if (!live[b.getBlockID()]) {
107 if (b.pred_begin() == b.pred_end()) {
108 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
109 // When not adding EH edges from calls, catch clauses
110 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000111 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000112 continue;
113 }
114 }
115 }
116
117 // Now we know what is live, we check the live precessors of the exit block
118 // and look for fall through paths, being careful to ignore normal returns,
119 // and exceptional paths.
120 bool HasLiveReturn = false;
121 bool HasFakeEdge = false;
122 bool HasPlainEdge = false;
123 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000124
125 // Ignore default cases that aren't likely to be reachable because all
126 // enums in a switch(X) have explicit case statements.
127 CFGBlock::FilterOptions FO;
128 FO.IgnoreDefaultsWithCoveredEnums = 1;
129
130 for (CFGBlock::filtered_pred_iterator
131 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
132 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000133 if (!live[B.getBlockID()])
134 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000135
136 // Destructors can appear after the 'return' in the CFG. This is
137 // normal. We need to look pass the destructors for the return
138 // statement (if it exists).
139 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000140 bool hasNoReturnDtor = false;
141
Ted Kremenek5811f592011-01-26 04:49:52 +0000142 for ( ; ri != re ; ++ri) {
143 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000144
145 // FIXME: The right solution is to just sever the edges in the
146 // CFG itself.
147 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
Ted Kremenekc5aff442011-03-03 01:21:32 +0000148 if (iDtor->isNoReturn(AC.getASTContext())) {
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000149 hasNoReturnDtor = true;
150 HasFakeEdge = true;
151 break;
152 }
153
Ted Kremenek5811f592011-01-26 04:49:52 +0000154 if (isa<CFGStmt>(CE))
155 break;
156 }
157
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000158 if (hasNoReturnDtor)
159 continue;
160
Ted Kremenek5811f592011-01-26 04:49:52 +0000161 // No more CFGElements in the block?
162 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000163 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
164 HasAbnormalEdge = true;
165 continue;
166 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000167 // A labeled empty statement, or the entry block...
168 HasPlainEdge = true;
169 continue;
170 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000171
Ted Kremenek5811f592011-01-26 04:49:52 +0000172 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000173 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000174 if (isa<ReturnStmt>(S)) {
175 HasLiveReturn = true;
176 continue;
177 }
178 if (isa<ObjCAtThrowStmt>(S)) {
179 HasFakeEdge = true;
180 continue;
181 }
182 if (isa<CXXThrowExpr>(S)) {
183 HasFakeEdge = true;
184 continue;
185 }
186 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
187 if (AS->isMSAsm()) {
188 HasFakeEdge = true;
189 HasLiveReturn = true;
190 continue;
191 }
192 }
193 if (isa<CXXTryStmt>(S)) {
194 HasAbnormalEdge = true;
195 continue;
196 }
197
198 bool NoReturnEdge = false;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000199 if (const CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000200 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
201 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000202 HasAbnormalEdge = true;
203 continue;
204 }
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000205 const Expr *CEE = C->getCallee()->IgnoreParenCasts();
John McCall1de85332011-05-11 07:19:11 +0000206 QualType calleeType = CEE->getType();
207 if (calleeType == AC.getASTContext().BoundMemberTy) {
208 calleeType = Expr::findBoundMemberType(CEE);
209 assert(!calleeType.isNull() && "analyzing unresolved call?");
210 }
211 if (getFunctionExtInfo(calleeType).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000212 NoReturnEdge = true;
213 HasFakeEdge = true;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000214 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
215 const ValueDecl *VD = DRE->getDecl();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000216 if (VD->hasAttr<NoReturnAttr>()) {
217 NoReturnEdge = true;
218 HasFakeEdge = true;
219 }
220 }
221 }
222 // FIXME: Add noreturn message sends.
223 if (NoReturnEdge == false)
224 HasPlainEdge = true;
225 }
226 if (!HasPlainEdge) {
227 if (HasLiveReturn)
228 return NeverFallThrough;
229 return NeverFallThroughOrReturn;
230 }
231 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
232 return MaybeFallThrough;
233 // This says AlwaysFallThrough for calls to functions that are not marked
234 // noreturn, that don't return. If people would like this warning to be more
235 // accurate, such functions should be marked as noreturn.
236 return AlwaysFallThrough;
237}
238
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000239namespace {
240
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000241struct CheckFallThroughDiagnostics {
242 unsigned diag_MaybeFallThrough_HasNoReturn;
243 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
244 unsigned diag_AlwaysFallThrough_HasNoReturn;
245 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
246 unsigned diag_NeverFallThroughOrReturn;
247 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000248 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000249
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000250 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000251 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000252 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000253 D.diag_MaybeFallThrough_HasNoReturn =
254 diag::warn_falloff_noreturn_function;
255 D.diag_MaybeFallThrough_ReturnsNonVoid =
256 diag::warn_maybe_falloff_nonvoid_function;
257 D.diag_AlwaysFallThrough_HasNoReturn =
258 diag::warn_falloff_noreturn_function;
259 D.diag_AlwaysFallThrough_ReturnsNonVoid =
260 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000261
262 // Don't suggest that virtual functions be marked "noreturn", since they
263 // might be overridden by non-noreturn functions.
264 bool isVirtualMethod = false;
265 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
266 isVirtualMethod = Method->isVirtual();
267
268 if (!isVirtualMethod)
269 D.diag_NeverFallThroughOrReturn =
270 diag::warn_suggest_noreturn_function;
271 else
272 D.diag_NeverFallThroughOrReturn = 0;
273
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000274 D.funMode = true;
275 return D;
276 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000277
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000278 static CheckFallThroughDiagnostics MakeForBlock() {
279 CheckFallThroughDiagnostics D;
280 D.diag_MaybeFallThrough_HasNoReturn =
281 diag::err_noreturn_block_has_return_expr;
282 D.diag_MaybeFallThrough_ReturnsNonVoid =
283 diag::err_maybe_falloff_nonvoid_block;
284 D.diag_AlwaysFallThrough_HasNoReturn =
285 diag::err_noreturn_block_has_return_expr;
286 D.diag_AlwaysFallThrough_ReturnsNonVoid =
287 diag::err_falloff_nonvoid_block;
288 D.diag_NeverFallThroughOrReturn =
289 diag::warn_suggest_noreturn_block;
290 D.funMode = false;
291 return D;
292 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000293
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000294 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
295 bool HasNoReturn) const {
296 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000297 return (ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
299 FuncLoc) == Diagnostic::Ignored)
300 && (!HasNoReturn ||
301 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
302 FuncLoc) == Diagnostic::Ignored)
303 && (!ReturnsVoid ||
304 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
305 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000306 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000307
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000308 // For blocks.
309 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000310 && (!ReturnsVoid ||
311 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
312 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000313 }
314};
315
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000316}
317
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000318/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
319/// function that should return a value. Check that we don't fall off the end
320/// of a noreturn function. We assume that functions and blocks not marked
321/// noreturn will return.
322static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000323 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000324 const CheckFallThroughDiagnostics& CD,
325 AnalysisContext &AC) {
326
327 bool ReturnsVoid = false;
328 bool HasNoReturn = false;
329
330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
331 ReturnsVoid = FD->getResultType()->isVoidType();
332 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000333 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000334 }
335 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
336 ReturnsVoid = MD->getResultType()->isVoidType();
337 HasNoReturn = MD->hasAttr<NoReturnAttr>();
338 }
339 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000340 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000341 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000342 BlockTy->getPointeeType()->getAs<FunctionType>()) {
343 if (FT->getResultType()->isVoidType())
344 ReturnsVoid = true;
345 if (FT->getNoReturnAttr())
346 HasNoReturn = true;
347 }
348 }
349
350 Diagnostic &Diags = S.getDiagnostics();
351
352 // Short circuit for compilation speed.
353 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
354 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000355
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000356 // FIXME: Function try block
357 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
358 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000359 case UnknownFallThrough:
360 break;
361
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000362 case MaybeFallThrough:
363 if (HasNoReturn)
364 S.Diag(Compound->getRBracLoc(),
365 CD.diag_MaybeFallThrough_HasNoReturn);
366 else if (!ReturnsVoid)
367 S.Diag(Compound->getRBracLoc(),
368 CD.diag_MaybeFallThrough_ReturnsNonVoid);
369 break;
370 case AlwaysFallThrough:
371 if (HasNoReturn)
372 S.Diag(Compound->getRBracLoc(),
373 CD.diag_AlwaysFallThrough_HasNoReturn);
374 else if (!ReturnsVoid)
375 S.Diag(Compound->getRBracLoc(),
376 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
377 break;
378 case NeverFallThroughOrReturn:
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000379 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000380 S.Diag(Compound->getLBracLoc(),
381 CD.diag_NeverFallThroughOrReturn);
382 break;
383 case NeverFallThrough:
384 break;
385 }
386 }
387}
388
389//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000390// -Wuninitialized
391//===----------------------------------------------------------------------===//
392
Ted Kremenek6f417152011-04-04 20:56:00 +0000393namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000394/// ContainsReference - A visitor class to search for references to
395/// a particular declaration (the needle) within any evaluated component of an
396/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000397class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000398 bool FoundReference;
399 const DeclRefExpr *Needle;
400
Ted Kremenek6f417152011-04-04 20:56:00 +0000401public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000402 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
403 : EvaluatedExprVisitor<ContainsReference>(Context),
404 FoundReference(false), Needle(Needle) {}
405
406 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000407 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000408 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000409 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000410
411 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000412 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000413
414 void VisitDeclRefExpr(DeclRefExpr *E) {
415 if (E == Needle)
416 FoundReference = true;
417 else
418 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000419 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000420
421 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000422};
423}
424
Chandler Carruth262d50e2011-04-05 18:27:05 +0000425/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
426/// uninitialized variable. This manages the different forms of diagnostic
427/// emitted for particular types of uses. Returns true if the use was diagnosed
428/// as a warning. If a pariticular use is one we omit warnings for, returns
429/// false.
430static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Chandler Carruth64fb9592011-04-05 18:18:08 +0000431 const Expr *E, bool isAlwaysUninit) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000432 bool isSelfInit = false;
433
434 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
435 if (isAlwaysUninit) {
436 // Inspect the initializer of the variable declaration which is
437 // being referenced prior to its initialization. We emit
438 // specialized diagnostics for self-initialization, and we
439 // specifically avoid warning about self references which take the
440 // form of:
441 //
442 // int x = x;
443 //
444 // This is used to indicate to GCC that 'x' is intentionally left
445 // uninitialized. Proven code paths which access 'x' in
446 // an uninitialized state after this will still warn.
447 //
448 // TODO: Should we suppress maybe-uninitialized warnings for
449 // variables initialized in this way?
450 if (const Expr *Initializer = VD->getInit()) {
451 if (DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000452 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000453
454 ContainsReference CR(S.Context, DRE);
455 CR.Visit(const_cast<Expr*>(Initializer));
456 isSelfInit = CR.doesContainReference();
457 }
458 if (isSelfInit) {
459 S.Diag(DRE->getLocStart(),
460 diag::warn_uninit_self_reference_in_init)
461 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
462 } else {
463 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
464 << VD->getDeclName() << DRE->getSourceRange();
465 }
466 } else {
467 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
468 << VD->getDeclName() << DRE->getSourceRange();
469 }
470 } else {
471 const BlockExpr *BE = cast<BlockExpr>(E);
472 S.Diag(BE->getLocStart(),
473 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
474 : diag::warn_maybe_uninit_var_captured_by_block)
475 << VD->getDeclName();
476 }
477
478 // Report where the variable was declared when the use wasn't within
479 // the initializer of that declaration.
480 if (!isSelfInit)
481 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
482 << VD->getDeclName();
483
Chandler Carruth262d50e2011-04-05 18:27:05 +0000484 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000485}
486
Chandler Carruth262d50e2011-04-05 18:27:05 +0000487static void SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000488 // Don't issue a fixit if there is already an initializer.
489 if (VD->getInit())
490 return;
491
492 // Suggest possible initialization (if any).
493 const char *initialization = 0;
494 QualType VariableTy = VD->getType().getCanonicalType();
495
Douglas Gregor8ba44262011-07-02 00:59:18 +0000496 if (VariableTy->isObjCObjectPointerType() ||
497 VariableTy->isBlockPointerType()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000498 // Check if 'nil' is defined.
499 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
500 initialization = " = nil";
501 else
502 initialization = " = 0";
503 }
504 else if (VariableTy->isRealFloatingType())
505 initialization = " = 0.0";
506 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
507 initialization = " = false";
508 else if (VariableTy->isEnumeralType())
509 return;
Douglas Gregor8ba44262011-07-02 00:59:18 +0000510 else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType()) {
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000511 if (S.Context.getLangOptions().CPlusPlus0x)
512 initialization = " = nullptr";
Douglas Gregor8ba44262011-07-02 00:59:18 +0000513 // Check if 'NULL' is defined.
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000514 else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL")))
Douglas Gregor8ba44262011-07-02 00:59:18 +0000515 initialization = " = NULL";
516 else
517 initialization = " = 0";
518 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000519 else if (VariableTy->isScalarType())
520 initialization = " = 0";
521
522 if (initialization) {
523 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
524 S.Diag(loc, diag::note_var_fixit_add_initialization)
525 << FixItHint::CreateInsertion(loc, initialization);
526 }
527}
528
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000529typedef std::pair<const Expr*, bool> UninitUse;
530
Ted Kremenek610068c2011-01-15 02:58:47 +0000531namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000532struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000533 bool operator()(const UninitUse &a, const UninitUse &b) {
534 SourceLocation aLoc = a.first->getLocStart();
535 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000536 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
537 }
538};
539
Ted Kremenek610068c2011-01-15 02:58:47 +0000540class UninitValsDiagReporter : public UninitVariablesHandler {
541 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000542 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000543 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
544 UsesMap *uses;
545
Ted Kremenek610068c2011-01-15 02:58:47 +0000546public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000547 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
548 ~UninitValsDiagReporter() {
549 flushDiagnostics();
550 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000551
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000552 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
553 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000554 if (!uses)
555 uses = new UsesMap();
556
557 UsesVec *&vec = (*uses)[vd];
558 if (!vec)
559 vec = new UsesVec();
560
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000561 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000562 }
563
564 void flushDiagnostics() {
565 if (!uses)
566 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000567
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000568 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
569 const VarDecl *vd = i->first;
570 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000571
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000572 // Sort the uses by their SourceLocations. While not strictly
573 // guaranteed to produce them in line/column order, this will provide
574 // a stable ordering.
575 std::sort(vec->begin(), vec->end(), SLocSort());
576
Chandler Carruth64fb9592011-04-05 18:18:08 +0000577 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
578 ++vi) {
Chandler Carruth262d50e2011-04-05 18:27:05 +0000579 if (!DiagnoseUninitializedUse(S, vd, vi->first,
580 /*isAlwaysUninit=*/vi->second))
581 continue;
582
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000583 SuggestInitializationFixit(S, vd);
584
585 // Skip further diagnostics for this variable. We try to warn only on
586 // the first point at which a variable is used uninitialized.
587 break;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000588 }
Ted Kremenekd40066b2011-04-04 23:29:12 +0000589
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000590 delete vec;
591 }
592 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000593 }
594};
595}
596
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000597
598//===----------------------------------------------------------------------===//
599// -Wthread-safety
600//===----------------------------------------------------------------------===//
601
602namespace {
603/// \brief Implements a set of CFGBlocks using a BitVector.
604///
605/// This class contains a minimal interface, primarily dictated by the SetType
606/// template parameter of the llvm::po_iterator template, as used with external
607/// storage. We also use this set to keep track of which CFGBlocks we visit
608/// during the analysis.
609class CFGBlockSet {
610 llvm::BitVector VisitedBlockIDs;
611
612public:
613 // po_iterator requires this iterator, but the only interface needed is the
614 // value_type typedef.
615 struct iterator {
616 typedef const CFGBlock *value_type;
617 };
618
619 CFGBlockSet() {}
620 CFGBlockSet(const CFG *G) : VisitedBlockIDs(G->getNumBlockIDs(), false) {}
621
622 /// \brief Set the bit associated with a particular CFGBlock.
623 /// This is the important method for the SetType template parameter.
624 bool insert(const CFGBlock *Block) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +0000625 // Note that insert() is called by po_iterator, which doesn't check to make
626 // sure that Block is non-null. Moreover, the CFGBlock iterator will
627 // occasionally hand out null pointers for pruned edges, so we catch those
628 // here.
629 if (Block == 0)
630 return false; // if an edge is trivially false.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000631 if (VisitedBlockIDs.test(Block->getBlockID()))
632 return false;
633 VisitedBlockIDs.set(Block->getBlockID());
634 return true;
635 }
636
637 /// \brief Check if the bit for a CFGBlock has been already set.
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +0000638 /// This method is for tracking visited blocks in the main threadsafety loop.
639 /// Block must not be null.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000640 bool alreadySet(const CFGBlock *Block) {
641 return VisitedBlockIDs.test(Block->getBlockID());
642 }
643};
644
645/// \brief We create a helper class which we use to iterate through CFGBlocks in
646/// the topological order.
647class TopologicallySortedCFG {
648 typedef llvm::po_iterator<const CFG*, CFGBlockSet, true> po_iterator;
649
650 std::vector<const CFGBlock*> Blocks;
651
652public:
653 typedef std::vector<const CFGBlock*>::reverse_iterator iterator;
654
655 TopologicallySortedCFG(const CFG *CFGraph) {
656 Blocks.reserve(CFGraph->getNumBlockIDs());
657 CFGBlockSet BSet(CFGraph);
658
659 for (po_iterator I = po_iterator::begin(CFGraph, BSet),
660 E = po_iterator::end(CFGraph, BSet); I != E; ++I) {
661 Blocks.push_back(*I);
662 }
663 }
664
665 iterator begin() {
666 return Blocks.rbegin();
667 }
668
669 iterator end() {
670 return Blocks.rend();
671 }
672};
673
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000674/// \brief A LockID object uniquely identifies a particular lock acquired, and
675/// is built from an Expr* (i.e. calling a lock function).
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000676///
677/// Thread-safety analysis works by comparing lock expressions. Within the
678/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
679/// a particular lock object at run-time. Subsequent occurrences of the same
680/// expression (where "same" means syntactic equality) will refer to the same
681/// run-time object if three conditions hold:
682/// (1) Local variables in the expression, such as "x" have not changed.
683/// (2) Values on the heap that affect the expression have not changed.
684/// (3) The expression involves only pure function calls.
685/// The current implementation assumes, but does not verify, that multiple uses
686/// of the same lock expression satisfies these criteria.
687///
688/// Clang introduces an additional wrinkle, which is that it is difficult to
689/// derive canonical expressions, or compare expressions directly for equality.
690/// Thus, we identify a lock not by an Expr, but by the set of named
691/// declarations that are referenced by the Expr. In other words,
692/// x->foo->bar.mu will be a four element vector with the Decls for
693/// mu, bar, and foo, and x. The vector will uniquely identify the expression
694/// for all practical purposes.
695///
696/// Note we will need to perform substitution on "this" and function parameter
697/// names when constructing a lock expression.
698///
699/// For example:
700/// class C { Mutex Mu; void lock() EXCLUSIVE_LOCK_FUNCTION(this->Mu); };
701/// void myFunc(C *X) { ... X->lock() ... }
702/// The original expression for the lock acquired by myFunc is "this->Mu", but
703/// "X" is substituted for "this" so we get X->Mu();
704///
705/// For another example:
706/// foo(MyList *L) EXCLUSIVE_LOCKS_REQUIRED(L->Mu) { ... }
707/// MyList *MyL;
708/// foo(MyL); // requires lock MyL->Mu to be held
709///
710/// FIXME: In C++0x Mutexes are the objects that control access to shared
711/// variables, while Locks are the objects that acquire and release Mutexes. We
712/// may want to switch to this new terminology soon, in which case we should
713/// rename this class "Mutex" and rename "LockId" to "MutexId", as well as
714/// making sure that the terms Lock and Mutex throughout this code are
715/// consistent with C++0x
716///
717/// FIXME: We should also pick one and canonicalize all usage of lock vs acquire
718/// and unlock vs release as verbs.
719class LockID {
720 SmallVector<NamedDecl*, 2> DeclSeq;
721
722 /// Build a Decl sequence representing the lock from the given expression.
723 /// Recursive function that bottoms out when the final DeclRefExpr is reached.
724 void buildLock(Expr *Exp) {
725 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
726 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
727 DeclSeq.push_back(ND);
728 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
729 NamedDecl *ND = ME->getMemberDecl();
730 DeclSeq.push_back(ND);
731 buildLock(ME->getBase());
732 } else {
733 // FIXME: add diagnostic
734 llvm::report_fatal_error("Expected lock expression!");
735 }
736 }
737
738public:
739 LockID(Expr *LExpr) {
740 buildLock(LExpr);
741 assert(!DeclSeq.empty());
742 }
743
744 bool operator==(const LockID &other) const {
745 return DeclSeq == other.DeclSeq;
746 }
747
748 bool operator!=(const LockID &other) const {
749 return !(*this == other);
750 }
751
752 // SmallVector overloads Operator< to do lexicographic ordering. Note that
753 // we use pointer equality (and <) to compare NamedDecls. This means the order
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000754 // of LockIDs in a lockset is nondeterministic. In order to output
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000755 // diagnostics in a deterministic ordering, we must order all diagnostics to
756 // output by SourceLocation when iterating through this lockset.
757 bool operator<(const LockID &other) const {
758 return DeclSeq < other.DeclSeq;
759 }
760
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000761 /// \brief Returns the name of the first Decl in the list for a given LockID;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000762 /// e.g. the lock expression foo.bar() has name "bar".
763 /// The caret will point unambiguously to the lock expression, so using this
764 /// name in diagnostics is a way to get simple, and consistent, lock names.
765 /// We do not want to output the entire expression text for security reasons.
766 StringRef getName() const {
767 return DeclSeq.front()->getName();
768 }
769
770 void Profile(llvm::FoldingSetNodeID &ID) const {
771 for (SmallVectorImpl<NamedDecl*>::const_iterator I = DeclSeq.begin(),
772 E = DeclSeq.end(); I != E; ++I) {
773 ID.AddPointer(*I);
774 }
775 }
776};
777
778/// \brief This is a helper class that stores info about the most recent
779/// accquire of a Lock.
780///
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000781/// The main body of the analysis maps LockIDs to LockDatas.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000782struct LockData {
783 SourceLocation AcquireLoc;
784
785 LockData(SourceLocation Loc) : AcquireLoc(Loc) {}
786
787 bool operator==(const LockData &other) const {
788 return AcquireLoc == other.AcquireLoc;
789 }
790
791 bool operator!=(const LockData &other) const {
792 return !(*this == other);
793 }
794
795 void Profile(llvm::FoldingSetNodeID &ID) const {
796 ID.AddInteger(AcquireLoc.getRawEncoding());
797 }
798};
799
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000800/// A Lockset maps each LockID (defined above) to information about how it has
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000801/// been locked.
802typedef llvm::ImmutableMap<LockID, LockData> Lockset;
803
804/// \brief We use this class to visit different types of expressions in
805/// CFGBlocks, and build up the lockset.
806/// An expression may cause us to add or remove locks from the lockset, or else
807/// output error messages related to missing locks.
808/// FIXME: In future, we may be able to not inherit from a visitor.
809class BuildLockset : public StmtVisitor<BuildLockset> {
810 Sema &S;
811 Lockset LSet;
812 Lockset::Factory &LocksetFactory;
813
814 // Helper functions
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000815 void removeLock(SourceLocation UnlockLoc, Expr *LockExp);
816 void addLock(SourceLocation LockLoc, Expr *LockExp);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000817 const ValueDecl *getValueDecl(Expr *Exp);
818 void checkAccess(Expr *Exp);
819 void checkDereference(Expr *Exp);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000820
821public:
822 BuildLockset(Sema &S, Lockset LS, Lockset::Factory &F)
823 : StmtVisitor<BuildLockset>(), S(S), LSet(LS),
824 LocksetFactory(F) {}
825
826 Lockset getLockset() {
827 return LSet;
828 }
829
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000830 void VisitUnaryOperator(UnaryOperator *UO);
831 void VisitBinaryOperator(BinaryOperator *BO);
832 void VisitCastExpr(CastExpr *CE);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000833 void VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp);
834};
835
836/// \brief Add a new lock to the lockset, warning if the lock is already there.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000837/// \param LockLoc The source location of the acquire
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000838/// \param LockExp The lock expression corresponding to the lock to be added
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000839void BuildLockset::addLock(SourceLocation LockLoc, Expr *LockExp) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000840 LockID Lock(LockExp);
841 LockData NewLockData(LockLoc);
842
843 if (LSet.contains(Lock))
844 S.Diag(LockLoc, diag::warn_double_lock) << Lock.getName();
845
846 LSet = LocksetFactory.add(LSet, Lock, NewLockData);
847}
848
849/// \brief Remove a lock from the lockset, warning if the lock is not there.
850/// \param LockExp The lock expression corresponding to the lock to be removed
851/// \param UnlockLoc The source location of the unlock (only used in error msg)
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000852void BuildLockset::removeLock(SourceLocation UnlockLoc, Expr *LockExp) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000853 LockID Lock(LockExp);
854
855 Lockset NewLSet = LocksetFactory.remove(LSet, Lock);
856 if(NewLSet == LSet)
857 S.Diag(UnlockLoc, diag::warn_unlock_but_no_acquire) << Lock.getName();
858
859 LSet = NewLSet;
860}
861
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000862/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
863const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
864 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
865 return DR->getDecl();
866
867 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
868 return ME->getMemberDecl();
869
870 return 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000871}
872
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000873/// \brief This method identifies variable dereferences and checks pt_guarded_by
874/// and pt_guarded_var annotations. Note that we only check these annotations
875/// at the time a pointer is dereferenced.
876/// FIXME: We need to check for other types of pointer dereferences
877/// (e.g. [], ->) and deal with them here.
878/// \param Exp An expression that has been read or written.
879void BuildLockset::checkDereference(Expr *Exp) {
880 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
881 if (!UO || UO->getOpcode() != clang::UO_Deref)
882 return;
883 Exp = UO->getSubExpr()->IgnoreParenCasts();
884
885 const ValueDecl *D = getValueDecl(Exp);
886 if(!D || !D->hasAttrs())
887 return;
888
889 if (D->getAttr<PtGuardedVarAttr>() && LSet.isEmpty())
890 S.Diag(Exp->getExprLoc(), diag::warn_var_deref_requires_any_lock)
891 << D->getName();
892
893 const AttrVec &ArgAttrs = D->getAttrs();
894 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i) {
895 if (ArgAttrs[i]->getKind() != attr::PtGuardedBy)
896 continue;
897 PtGuardedByAttr *PGBAttr = cast<PtGuardedByAttr>(ArgAttrs[i]);
898 LockID Lock(PGBAttr->getArg());
899 if (!LSet.contains(Lock))
900 S.Diag(Exp->getExprLoc(), diag::warn_var_deref_requires_lock)
901 << D->getName() << Lock.getName();
902 }
903}
904
905/// \brief Checks guarded_by and guarded_var attributes.
906/// Whenever we identify an access (read or write) of a DeclRefExpr or
907/// MemberExpr, we need to check whether there are any guarded_by or
908/// guarded_var attributes, and make sure we hold the appropriate locks.
909void BuildLockset::checkAccess(Expr *Exp) {
910 const ValueDecl *D = getValueDecl(Exp);
911 if(!D || !D->hasAttrs())
912 return;
913
914 if (D->getAttr<GuardedVarAttr>() && LSet.isEmpty())
915 S.Diag(Exp->getExprLoc(), diag::warn_variable_requires_any_lock)
916 << D->getName();
917
918 const AttrVec &ArgAttrs = D->getAttrs();
919 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i) {
920 if (ArgAttrs[i]->getKind() != attr::GuardedBy)
921 continue;
922 GuardedByAttr *GBAttr = cast<GuardedByAttr>(ArgAttrs[i]);
923 LockID Lock(GBAttr->getArg());
924 if (!LSet.contains(Lock))
925 S.Diag(Exp->getExprLoc(), diag::warn_variable_requires_lock)
926 << D->getName() << Lock.getName();
927 }
928}
929
930/// \brief For unary operations which read and write a variable, we need to
931/// check whether we hold any required locks. Reads are checked in
932/// VisitCastExpr.
933void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
934 switch (UO->getOpcode()) {
935 case clang::UO_PostDec:
936 case clang::UO_PostInc:
937 case clang::UO_PreDec:
938 case clang::UO_PreInc: {
939 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
940 checkAccess(SubExp);
941 checkDereference(SubExp);
942 break;
943 }
944 default:
945 break;
946 }
947}
948
949/// For binary operations which assign to a variable (writes), we need to check
950/// whether we hold any required locks.
951/// FIXME: Deal with non-primitive types.
952void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
953 if (!BO->isAssignmentOp())
954 return;
955 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
956 checkAccess(LHSExp);
957 checkDereference(LHSExp);
958}
959
960/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
961/// need to ensure we hold any required locks.
962/// FIXME: Deal with non-primitive types.
963void BuildLockset::VisitCastExpr(CastExpr *CE) {
964 if (CE->getCastKind() != CK_LValueToRValue)
965 return;
966 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
967 checkAccess(SubExp);
968 checkDereference(SubExp);
969}
970
971
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000972/// \brief When visiting CXXMemberCallExprs we need to examine the attributes on
973/// the method that is being called and add, remove or check locks in the
974/// lockset accordingly.
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000975///
976/// FIXME: For classes annotated with one of the guarded annotations, we need
977/// to treat const method calls as reads and non-const method calls as writes,
978/// and check that the appropriate locks are held. Non-const method calls with
979/// the same signature as const method calls can be also treated as reads.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000980void BuildLockset::VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +0000981 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
982
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000983 SourceLocation ExpLocation = Exp->getExprLoc();
984 Expr *Parent = Exp->getImplicitObjectArgument();
985
986 if(!D || !D->hasAttrs())
987 return;
988
989 AttrVec &ArgAttrs = D->getAttrs();
990 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
991 Attr *Attr = ArgAttrs[i];
992 switch (Attr->getKind()) {
993 // When we encounter an exclusive lock function, we need to add the lock
994 // to our lockset.
995 case attr::ExclusiveLockFunction: {
996 ExclusiveLockFunctionAttr *ELFAttr =
997 cast<ExclusiveLockFunctionAttr>(Attr);
998
999 if (ELFAttr->args_size() == 0) {// The lock held is the "this" object.
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001000 addLock(ExpLocation, Parent);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001001 break;
1002 }
1003
1004 for (ExclusiveLockFunctionAttr::args_iterator I = ELFAttr->args_begin(),
1005 E = ELFAttr->args_end(); I != E; ++I)
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001006 addLock(ExpLocation, *I);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001007 // FIXME: acquired_after/acquired_before annotations
1008 break;
1009 }
1010
1011 // When we encounter an unlock function, we need to remove unlocked locks
1012 // from the lockset, and flag a warning if they are not there.
1013 case attr::UnlockFunction: {
1014 UnlockFunctionAttr *UFAttr = cast<UnlockFunctionAttr>(Attr);
1015
1016 if (UFAttr->args_size() == 0) { // The lock held is the "this" object.
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001017 removeLock(ExpLocation, Parent);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001018 break;
1019 }
1020
1021 for (UnlockFunctionAttr::args_iterator I = UFAttr->args_begin(),
1022 E = UFAttr->args_end(); I != E; ++I)
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001023 removeLock(ExpLocation, *I);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001024 break;
1025 }
1026
1027 // Ignore other (non thread-safety) attributes
1028 default:
1029 break;
1030 }
1031 }
1032}
1033
1034typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag;
1035typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
1036
1037struct SortDiagBySourceLocation {
1038 Sema &S;
1039
1040 SortDiagBySourceLocation(Sema &S) : S(S) {}
1041
1042 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1043 // Although this call will be slow, this is only called when outputting
1044 // multiple warnings.
1045 return S.getSourceManager().isBeforeInTranslationUnit(left.first,
1046 right.first);
1047 }
1048};
1049} // end anonymous namespace
1050
1051/// \brief Emit all buffered diagnostics in order of sourcelocation.
1052/// We need to output diagnostics produced while iterating through
1053/// the lockset in deterministic order, so this function orders diagnostics
1054/// and outputs them.
1055static void EmitDiagnostics(Sema &S, DiagList &D) {
1056 SortDiagBySourceLocation SortDiagBySL(S);
1057 sort(D.begin(), D.end(), SortDiagBySL);
1058 for (DiagList::iterator I = D.begin(), E = D.end(); I != E; ++I)
1059 S.Diag(I->first, I->second);
1060}
1061
1062/// \brief Compute the intersection of two locksets and issue warnings for any
1063/// locks in the symmetric difference.
1064///
1065/// This function is used at a merge point in the CFG when comparing the lockset
1066/// of each branch being merged. For example, given the following sequence:
1067/// A; if () then B; else C; D; we need to check that the lockset after B and C
1068/// are the same. In the event of a difference, we use the intersection of these
1069/// two locksets at the start of D.
1070static Lockset intersectAndWarn(Sema &S, Lockset LSet1, Lockset LSet2,
1071 Lockset::Factory &Fact) {
1072 Lockset Intersection = LSet1;
1073 DiagList Warnings;
1074
1075 for (Lockset::iterator I = LSet2.begin(), E = LSet2.end(); I != E; ++I) {
1076 if (!LSet1.contains(I.getKey())) {
1077 const LockID &MissingLock = I.getKey();
1078 const LockData &MissingLockData = I.getData();
1079 PartialDiagnostic Warning =
1080 S.PDiag(diag::warn_lock_not_released_in_scope) << MissingLock.getName();
1081 Warnings.push_back(DelayedDiag(MissingLockData.AcquireLoc, Warning));
1082 }
1083 }
1084
1085 for (Lockset::iterator I = LSet1.begin(), E = LSet1.end(); I != E; ++I) {
1086 if (!LSet2.contains(I.getKey())) {
1087 const LockID &MissingLock = I.getKey();
1088 const LockData &MissingLockData = I.getData();
1089 PartialDiagnostic Warning =
1090 S.PDiag(diag::warn_lock_not_released_in_scope) << MissingLock.getName();
1091 Warnings.push_back(DelayedDiag(MissingLockData.AcquireLoc, Warning));
1092 Intersection = Fact.remove(Intersection, MissingLock);
1093 }
1094 }
1095
1096 EmitDiagnostics(S, Warnings);
1097 return Intersection;
1098}
1099
1100/// \brief Returns the location of the first Stmt in a Block.
1101static SourceLocation getFirstStmtLocation(CFGBlock *Block) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001102 SourceLocation Loc;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001103 for (CFGBlock::const_iterator BI = Block->begin(), BE = Block->end();
1104 BI != BE; ++BI) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001105 if (const CFGStmt *CfgStmt = dyn_cast<CFGStmt>(&(*BI))) {
1106 Loc = CfgStmt->getStmt()->getLocStart();
1107 if (Loc.isValid()) return Loc;
1108 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001109 }
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001110 if (Stmt *S = Block->getTerminator().getStmt()) {
1111 Loc = S->getLocStart();
1112 if (Loc.isValid()) return Loc;
1113 }
1114 return Loc;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001115}
1116
1117/// \brief Warn about different locksets along backedges of loops.
1118/// This function is called when we encounter a back edge. At that point,
1119/// we need to verify that the lockset before taking the backedge is the
1120/// same as the lockset before entering the loop.
1121///
1122/// \param LoopEntrySet Locks held before starting the loop
1123/// \param LoopReentrySet Locks held in the last CFG block of the loop
1124static void warnBackEdgeUnequalLocksets(Sema &S, const Lockset LoopReentrySet,
1125 const Lockset LoopEntrySet,
1126 SourceLocation FirstLocInLoop) {
1127 assert(FirstLocInLoop.isValid());
1128 DiagList Warnings;
1129
1130 // Warn for locks held at the start of the loop, but not the end.
1131 for (Lockset::iterator I = LoopEntrySet.begin(), E = LoopEntrySet.end();
1132 I != E; ++I) {
1133 if (!LoopReentrySet.contains(I.getKey())) {
1134 const LockID &MissingLock = I.getKey();
1135 // We report this error at the location of the first statement in a loop
1136 PartialDiagnostic Warning =
1137 S.PDiag(diag::warn_expecting_lock_held_on_loop)
1138 << MissingLock.getName();
1139 Warnings.push_back(DelayedDiag(FirstLocInLoop, Warning));
1140 }
1141 }
1142
1143 // Warn for locks held at the end of the loop, but not at the start.
1144 for (Lockset::iterator I = LoopReentrySet.begin(), E = LoopReentrySet.end();
1145 I != E; ++I) {
1146 if (!LoopEntrySet.contains(I.getKey())) {
1147 const LockID &MissingLock = I.getKey();
1148 const LockData &MissingLockData = I.getData();
1149 PartialDiagnostic Warning =
1150 S.PDiag(diag::warn_lock_not_released_in_scope) << MissingLock.getName();
1151 Warnings.push_back(DelayedDiag(MissingLockData.AcquireLoc, Warning));
1152 }
1153 }
1154
1155 EmitDiagnostics(S, Warnings);
1156}
1157
1158/// \brief Check a function's CFG for thread-safety violations.
1159///
1160/// We traverse the blocks in the CFG, compute the set of locks that are held
1161/// at the end of each block, and issue warnings for thread safety violations.
1162/// Each block in the CFG is traversed exactly once.
1163static void checkThreadSafety(Sema &S, AnalysisContext &AC) {
1164 CFG *CFGraph = AC.getCFG();
1165 if (!CFGraph) return;
1166
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001167 Lockset::Factory LocksetFactory;
1168
1169 // FIXME: Swith to SmallVector? Otherwise improve performance impact?
1170 std::vector<Lockset> EntryLocksets(CFGraph->getNumBlockIDs(),
1171 LocksetFactory.getEmptyMap());
1172 std::vector<Lockset> ExitLocksets(CFGraph->getNumBlockIDs(),
1173 LocksetFactory.getEmptyMap());
1174
1175 // We need to explore the CFG via a "topological" ordering.
1176 // That way, we will be guaranteed to have information about required
1177 // predecessor locksets when exploring a new block.
1178 TopologicallySortedCFG SortedGraph(CFGraph);
1179 CFGBlockSet VisitedBlocks(CFGraph);
1180
1181 for (TopologicallySortedCFG::iterator I = SortedGraph.begin(),
1182 E = SortedGraph.end(); I!= E; ++I) {
1183 const CFGBlock *CurrBlock = *I;
1184 int CurrBlockID = CurrBlock->getBlockID();
1185
1186 VisitedBlocks.insert(CurrBlock);
1187
1188 // Use the default initial lockset in case there are no predecessors.
1189 Lockset &Entryset = EntryLocksets[CurrBlockID];
1190 Lockset &Exitset = ExitLocksets[CurrBlockID];
1191
1192 // Iterate through the predecessor blocks and warn if the lockset for all
1193 // predecessors is not the same. We take the entry lockset of the current
1194 // block to be the intersection of all previous locksets.
1195 // FIXME: By keeping the intersection, we may output more errors in future
1196 // for a lock which is not in the intersection, but was in the union. We
1197 // may want to also keep the union in future. As an example, let's say
1198 // the intersection contains Lock L, and the union contains L and M.
1199 // Later we unlock M. At this point, we would output an error because we
1200 // never locked M; although the real error is probably that we forgot to
1201 // lock M on all code paths. Conversely, let's say that later we lock M.
1202 // In this case, we should compare against the intersection instead of the
1203 // union because the real error is probably that we forgot to unlock M on
1204 // all code paths.
1205 bool LocksetInitialized = false;
1206 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1207 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1208
1209 // if *PI -> CurrBlock is a back edge
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001210 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001211 continue;
1212
1213 int PrevBlockID = (*PI)->getBlockID();
1214 if (!LocksetInitialized) {
1215 Entryset = ExitLocksets[PrevBlockID];
1216 LocksetInitialized = true;
1217 } else {
1218 Entryset = intersectAndWarn(S, Entryset, ExitLocksets[PrevBlockID],
1219 LocksetFactory);
1220 }
1221 }
1222
1223 BuildLockset LocksetBuilder(S, Entryset, LocksetFactory);
1224 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1225 BE = CurrBlock->end(); BI != BE; ++BI) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001226 if (const CFGStmt *CfgStmt = dyn_cast<CFGStmt>(&*BI))
Ted Kremenekf1d10d92011-08-23 23:05:04 +00001227 LocksetBuilder.Visit(const_cast<Stmt*>(CfgStmt->getStmt()));
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001228 }
1229 Exitset = LocksetBuilder.getLockset();
1230
1231 // For every back edge from CurrBlock (the end of the loop) to another block
1232 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
1233 // the one held at the beginning of FirstLoopBlock. We can look up the
1234 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
1235 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1236 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1237
1238 // if CurrBlock -> *SI is *not* a back edge
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001239 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001240 continue;
1241
1242 CFGBlock *FirstLoopBlock = *SI;
1243 SourceLocation FirstLoopLocation = getFirstStmtLocation(FirstLoopBlock);
1244
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001245 assert(FirstLoopLocation.isValid());
1246 // Fail gracefully in release code.
1247 if (!FirstLoopLocation.isValid())
1248 continue;
1249
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001250 Lockset PreLoop = EntryLocksets[FirstLoopBlock->getBlockID()];
1251 Lockset LoopEnd = ExitLocksets[CurrBlockID];
1252 warnBackEdgeUnequalLocksets(S, LoopEnd, PreLoop, FirstLoopLocation);
1253 }
1254 }
1255
1256 Lockset FinalLockset = ExitLocksets[CFGraph->getExit().getBlockID()];
1257 if (!FinalLockset.isEmpty()) {
1258 DiagList Warnings;
1259 for (Lockset::iterator I=FinalLockset.begin(), E=FinalLockset.end();
1260 I != E; ++I) {
1261 const LockID &MissingLock = I.getKey();
1262 const LockData &MissingLockData = I.getData();
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001263
1264 std::string FunName = "<unknown>";
1265 if (const NamedDecl *ContextDecl = dyn_cast<NamedDecl>(AC.getDecl())) {
1266 FunName = ContextDecl->getDeclName().getAsString();
1267 }
1268
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001269 PartialDiagnostic Warning =
1270 S.PDiag(diag::warn_locks_not_released)
1271 << MissingLock.getName() << FunName;
1272 Warnings.push_back(DelayedDiag(MissingLockData.AcquireLoc, Warning));
1273 }
1274 EmitDiagnostics(S, Warnings);
1275 }
1276}
1277
1278
Ted Kremenek610068c2011-01-15 02:58:47 +00001279//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001280// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1281// warnings on a function, method, or block.
1282//===----------------------------------------------------------------------===//
1283
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001284clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1285 enableCheckFallThrough = 1;
1286 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001287 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001288}
1289
Chandler Carruth5d989942011-07-06 16:21:37 +00001290clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1291 : S(s),
1292 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001293 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001294 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001295 MaxCFGBlocksPerFunction(0),
1296 NumUninitAnalysisFunctions(0),
1297 NumUninitAnalysisVariables(0),
1298 MaxUninitAnalysisVariablesPerFunction(0),
1299 NumUninitAnalysisBlockVisits(0),
1300 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001301 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001302 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001303 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
1304 Diagnostic::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001305 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1306 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
1307 Diagnostic::Ignored);
1308
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001309}
1310
Ted Kremenek351ba912011-02-23 01:52:04 +00001311static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001312 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001313 i = fscope->PossiblyUnreachableDiags.begin(),
1314 e = fscope->PossiblyUnreachableDiags.end();
1315 i != e; ++i) {
1316 const sema::PossiblyUnreachableDiag &D = *i;
1317 S.Diag(D.Loc, D.PD);
1318 }
1319}
1320
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001321void clang::sema::
1322AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001323 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001324 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001325
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001326 // We avoid doing analysis-based warnings when there are errors for
1327 // two reasons:
1328 // (1) The CFGs often can't be constructed (if the body is invalid), so
1329 // don't bother trying.
1330 // (2) The code already has problems; running the analysis just takes more
1331 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +00001332 Diagnostic &Diags = S.getDiagnostics();
1333
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001334 // Do not do any analysis for declarations in system headers if we are
1335 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001336 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001337 S.SourceMgr.isInSystemHeader(D->getLocation()))
1338 return;
1339
John McCalle0054f62010-08-25 05:56:39 +00001340 // For code in dependent contexts, we'll do this at instantiation time.
1341 if (cast<DeclContext>(D)->isDependentContext())
1342 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001343
Ted Kremenek351ba912011-02-23 01:52:04 +00001344 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1345 // Flush out any possibly unreachable diagnostics.
1346 flushDiagnostics(S, fscope);
1347 return;
1348 }
1349
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001350 const Stmt *Body = D->getBody();
1351 assert(Body);
1352
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001353 AnalysisContext AC(D, 0);
1354
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001355 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1356 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001357 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1358 AC.getCFGBuildOptions().AddEHEdges = false;
1359 AC.getCFGBuildOptions().AddInitializers = true;
1360 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001361
1362 // Force that certain expressions appear as CFGElements in the CFG. This
1363 // is used to speed up various analyses.
1364 // FIXME: This isn't the right factoring. This is here for initial
1365 // prototyping, but we need a way for analyses to say what expressions they
1366 // expect to always be CFGElements and then fill in the BuildOptions
1367 // appropriately. This is essentially a layering violation.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001368 if (P.enableCheckUnreachable) {
1369 // Unreachable code analysis requires a linearized CFG.
1370 AC.getCFGBuildOptions().setAllAlwaysAdd();
1371 }
1372 else {
1373 AC.getCFGBuildOptions()
1374 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1375 .setAlwaysAdd(Stmt::BlockExprClass)
1376 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1377 .setAlwaysAdd(Stmt::DeclRefExprClass)
1378 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1379 .setAlwaysAdd(Stmt::UnaryOperatorClass);
1380 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001381
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001382 // Construct the analysis context with the specified CFG build options.
1383
Ted Kremenek351ba912011-02-23 01:52:04 +00001384 // Emit delayed diagnostics.
1385 if (!fscope->PossiblyUnreachableDiags.empty()) {
1386 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001387
1388 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001389 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001390 i = fscope->PossiblyUnreachableDiags.begin(),
1391 e = fscope->PossiblyUnreachableDiags.end();
1392 i != e; ++i) {
1393 if (const Stmt *stmt = i->stmt)
1394 AC.registerForcedBlockExpression(stmt);
1395 }
1396
1397 if (AC.getCFG()) {
1398 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001399 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001400 i = fscope->PossiblyUnreachableDiags.begin(),
1401 e = fscope->PossiblyUnreachableDiags.end();
1402 i != e; ++i)
1403 {
1404 const sema::PossiblyUnreachableDiag &D = *i;
1405 bool processed = false;
1406 if (const Stmt *stmt = i->stmt) {
1407 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
1408 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +00001409 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001410 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001411 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001412 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001413 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001414 }
1415 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001416 if (!processed) {
1417 // Emit the warning anyway if we cannot map to a basic block.
1418 S.Diag(D.Loc, D.PD);
1419 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001420 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001421 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001422
1423 if (!analyzed)
1424 flushDiagnostics(S, fscope);
1425 }
1426
1427
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001428 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001429 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001430 const CheckFallThroughDiagnostics &CD =
1431 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +00001432 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001433 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001434 }
1435
1436 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +00001437 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001438 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +00001439
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001440 // Check for thread safety violations
1441 if (P.enableThreadSafetyAnalysis)
1442 checkThreadSafety(S, AC);
1443
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001444 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +00001445 != Diagnostic::Ignored ||
1446 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +00001447 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001448 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001449 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001450 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001451 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001452 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001453 reporter, stats);
1454
1455 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1456 ++NumUninitAnalysisFunctions;
1457 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1458 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1459 MaxUninitAnalysisVariablesPerFunction =
1460 std::max(MaxUninitAnalysisVariablesPerFunction,
1461 stats.NumVariablesAnalyzed);
1462 MaxUninitAnalysisBlockVisitsPerFunction =
1463 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1464 stats.NumBlockVisits);
1465 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001466 }
1467 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001468
1469 // Collect statistics about the CFG if it was built.
1470 if (S.CollectStats && AC.isCFGBuilt()) {
1471 ++NumFunctionsAnalyzed;
1472 if (CFG *cfg = AC.getCFG()) {
1473 // If we successfully built a CFG for this context, record some more
1474 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001475 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001476 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001477 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001478 } else {
1479 ++NumFunctionsWithBadCFGs;
1480 }
1481 }
1482}
1483
1484void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1485 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1486
1487 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1488 unsigned AvgCFGBlocksPerFunction =
1489 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1490 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1491 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1492 << " " << NumCFGBlocks << " CFG blocks built.\n"
1493 << " " << AvgCFGBlocksPerFunction
1494 << " average CFG blocks per function.\n"
1495 << " " << MaxCFGBlocksPerFunction
1496 << " max CFG blocks per function.\n";
1497
1498 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1499 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1500 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1501 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1502 llvm::errs() << NumUninitAnalysisFunctions
1503 << " functions analyzed for uninitialiazed variables\n"
1504 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1505 << " " << AvgUninitVariablesPerFunction
1506 << " average variables per function.\n"
1507 << " " << MaxUninitAnalysisVariablesPerFunction
1508 << " max variables per function.\n"
1509 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1510 << " " << AvgUninitBlockVisitsPerFunction
1511 << " average block visits per function.\n"
1512 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1513 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001514}