blob: 2da5568b592357fc66dd4e005725467ae5f66474 [file] [log] [blame]
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000018#include "clang/Sema/ScopeInfo.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000019#include "clang/Basic/SourceManager.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000020#include "clang/Basic/SourceLocation.h"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000021#include "clang/Lex/Preprocessor.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000024#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000029#include "clang/AST/StmtVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000030#include "clang/Analysis/AnalysisContext.h"
31#include "clang/Analysis/CFG.h"
32#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000033#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
34#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000035#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000036#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000037#include "llvm/ADT/FoldingSet.h"
38#include "llvm/ADT/ImmutableMap.h"
39#include "llvm/ADT/PostOrderIterator.h"
40#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +000041#include "llvm/ADT/StringRef.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000042#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000043#include <algorithm>
44#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000045
46using namespace clang;
47
48//===----------------------------------------------------------------------===//
49// Unreachable code analysis.
50//===----------------------------------------------------------------------===//
51
52namespace {
53 class UnreachableCodeHandler : public reachable_code::Callback {
54 Sema &S;
55 public:
56 UnreachableCodeHandler(Sema &s) : S(s) {}
57
58 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
59 S.Diag(L, diag::warn_unreachable) << R1 << R2;
60 }
61 };
62}
63
64/// CheckUnreachable - Check for unreachable code.
65static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
66 UnreachableCodeHandler UC(S);
67 reachable_code::FindUnreachableCode(AC, UC);
68}
69
70//===----------------------------------------------------------------------===//
71// Check for missing return value.
72//===----------------------------------------------------------------------===//
73
John McCall16565aa2010-05-16 09:34:11 +000074enum ControlFlowKind {
75 UnknownFallThrough,
76 NeverFallThrough,
77 MaybeFallThrough,
78 AlwaysFallThrough,
79 NeverFallThroughOrReturn
80};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000081
82/// CheckFallThrough - Check that we don't fall off the end of a
83/// Statement that should return a value.
84///
85/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
86/// MaybeFallThrough iff we might or might not fall off the end,
87/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
88/// return. We assume NeverFallThrough iff we never fall off the end of the
89/// statement but we may return. We assume that functions not marked noreturn
90/// will return.
91static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
92 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000093 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000094
95 // The CFG leaves in dead things, and we don't want the dead code paths to
96 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000097 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +000098 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000099 live);
100
101 bool AddEHEdges = AC.getAddEHEdges();
102 if (!AddEHEdges && count != cfg->getNumBlockIDs())
103 // When there are things remaining dead, and we didn't add EH edges
104 // from CallExprs to the catch clauses, we have to go back and
105 // mark them as live.
106 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
107 CFGBlock &b = **I;
108 if (!live[b.getBlockID()]) {
109 if (b.pred_begin() == b.pred_end()) {
110 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
111 // When not adding EH edges from calls, catch clauses
112 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000113 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000114 continue;
115 }
116 }
117 }
118
119 // Now we know what is live, we check the live precessors of the exit block
120 // and look for fall through paths, being careful to ignore normal returns,
121 // and exceptional paths.
122 bool HasLiveReturn = false;
123 bool HasFakeEdge = false;
124 bool HasPlainEdge = false;
125 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000126
127 // Ignore default cases that aren't likely to be reachable because all
128 // enums in a switch(X) have explicit case statements.
129 CFGBlock::FilterOptions FO;
130 FO.IgnoreDefaultsWithCoveredEnums = 1;
131
132 for (CFGBlock::filtered_pred_iterator
133 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
134 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000135 if (!live[B.getBlockID()])
136 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000137
138 // Destructors can appear after the 'return' in the CFG. This is
139 // normal. We need to look pass the destructors for the return
140 // statement (if it exists).
141 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000142 bool hasNoReturnDtor = false;
143
Ted Kremenek5811f592011-01-26 04:49:52 +0000144 for ( ; ri != re ; ++ri) {
145 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000146
147 // FIXME: The right solution is to just sever the edges in the
148 // CFG itself.
149 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
Ted Kremenekc5aff442011-03-03 01:21:32 +0000150 if (iDtor->isNoReturn(AC.getASTContext())) {
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000151 hasNoReturnDtor = true;
152 HasFakeEdge = true;
153 break;
154 }
155
Ted Kremenek5811f592011-01-26 04:49:52 +0000156 if (isa<CFGStmt>(CE))
157 break;
158 }
159
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000160 if (hasNoReturnDtor)
161 continue;
162
Ted Kremenek5811f592011-01-26 04:49:52 +0000163 // No more CFGElements in the block?
164 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000165 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
166 HasAbnormalEdge = true;
167 continue;
168 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000169 // A labeled empty statement, or the entry block...
170 HasPlainEdge = true;
171 continue;
172 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000173
Ted Kremenek5811f592011-01-26 04:49:52 +0000174 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000175 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000176 if (isa<ReturnStmt>(S)) {
177 HasLiveReturn = true;
178 continue;
179 }
180 if (isa<ObjCAtThrowStmt>(S)) {
181 HasFakeEdge = true;
182 continue;
183 }
184 if (isa<CXXThrowExpr>(S)) {
185 HasFakeEdge = true;
186 continue;
187 }
188 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
189 if (AS->isMSAsm()) {
190 HasFakeEdge = true;
191 HasLiveReturn = true;
192 continue;
193 }
194 }
195 if (isa<CXXTryStmt>(S)) {
196 HasAbnormalEdge = true;
197 continue;
198 }
199
200 bool NoReturnEdge = false;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000201 if (const CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000202 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
203 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000204 HasAbnormalEdge = true;
205 continue;
206 }
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000207 const Expr *CEE = C->getCallee()->IgnoreParenCasts();
John McCall1de85332011-05-11 07:19:11 +0000208 QualType calleeType = CEE->getType();
209 if (calleeType == AC.getASTContext().BoundMemberTy) {
210 calleeType = Expr::findBoundMemberType(CEE);
211 assert(!calleeType.isNull() && "analyzing unresolved call?");
212 }
213 if (getFunctionExtInfo(calleeType).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000214 NoReturnEdge = true;
215 HasFakeEdge = true;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000216 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
217 const ValueDecl *VD = DRE->getDecl();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000218 if (VD->hasAttr<NoReturnAttr>()) {
219 NoReturnEdge = true;
220 HasFakeEdge = true;
221 }
222 }
223 }
224 // FIXME: Add noreturn message sends.
225 if (NoReturnEdge == false)
226 HasPlainEdge = true;
227 }
228 if (!HasPlainEdge) {
229 if (HasLiveReturn)
230 return NeverFallThrough;
231 return NeverFallThroughOrReturn;
232 }
233 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
234 return MaybeFallThrough;
235 // This says AlwaysFallThrough for calls to functions that are not marked
236 // noreturn, that don't return. If people would like this warning to be more
237 // accurate, such functions should be marked as noreturn.
238 return AlwaysFallThrough;
239}
240
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000241namespace {
242
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000243struct CheckFallThroughDiagnostics {
244 unsigned diag_MaybeFallThrough_HasNoReturn;
245 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
246 unsigned diag_AlwaysFallThrough_HasNoReturn;
247 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
248 unsigned diag_NeverFallThroughOrReturn;
249 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000250 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000251
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000252 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000253 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000254 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000255 D.diag_MaybeFallThrough_HasNoReturn =
256 diag::warn_falloff_noreturn_function;
257 D.diag_MaybeFallThrough_ReturnsNonVoid =
258 diag::warn_maybe_falloff_nonvoid_function;
259 D.diag_AlwaysFallThrough_HasNoReturn =
260 diag::warn_falloff_noreturn_function;
261 D.diag_AlwaysFallThrough_ReturnsNonVoid =
262 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000263
264 // Don't suggest that virtual functions be marked "noreturn", since they
265 // might be overridden by non-noreturn functions.
266 bool isVirtualMethod = false;
267 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
268 isVirtualMethod = Method->isVirtual();
269
270 if (!isVirtualMethod)
271 D.diag_NeverFallThroughOrReturn =
272 diag::warn_suggest_noreturn_function;
273 else
274 D.diag_NeverFallThroughOrReturn = 0;
275
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000276 D.funMode = true;
277 return D;
278 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000279
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000280 static CheckFallThroughDiagnostics MakeForBlock() {
281 CheckFallThroughDiagnostics D;
282 D.diag_MaybeFallThrough_HasNoReturn =
283 diag::err_noreturn_block_has_return_expr;
284 D.diag_MaybeFallThrough_ReturnsNonVoid =
285 diag::err_maybe_falloff_nonvoid_block;
286 D.diag_AlwaysFallThrough_HasNoReturn =
287 diag::err_noreturn_block_has_return_expr;
288 D.diag_AlwaysFallThrough_ReturnsNonVoid =
289 diag::err_falloff_nonvoid_block;
290 D.diag_NeverFallThroughOrReturn =
291 diag::warn_suggest_noreturn_block;
292 D.funMode = false;
293 return D;
294 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000295
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000296 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
297 bool HasNoReturn) const {
298 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000299 return (ReturnsVoid ||
300 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
301 FuncLoc) == Diagnostic::Ignored)
302 && (!HasNoReturn ||
303 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
304 FuncLoc) == Diagnostic::Ignored)
305 && (!ReturnsVoid ||
306 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
307 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000308 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000309
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000310 // For blocks.
311 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000312 && (!ReturnsVoid ||
313 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
314 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000315 }
316};
317
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000318}
319
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000320/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
321/// function that should return a value. Check that we don't fall off the end
322/// of a noreturn function. We assume that functions and blocks not marked
323/// noreturn will return.
324static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000325 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000326 const CheckFallThroughDiagnostics& CD,
327 AnalysisContext &AC) {
328
329 bool ReturnsVoid = false;
330 bool HasNoReturn = false;
331
332 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
333 ReturnsVoid = FD->getResultType()->isVoidType();
334 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000335 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000336 }
337 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
338 ReturnsVoid = MD->getResultType()->isVoidType();
339 HasNoReturn = MD->hasAttr<NoReturnAttr>();
340 }
341 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000342 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000343 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000344 BlockTy->getPointeeType()->getAs<FunctionType>()) {
345 if (FT->getResultType()->isVoidType())
346 ReturnsVoid = true;
347 if (FT->getNoReturnAttr())
348 HasNoReturn = true;
349 }
350 }
351
352 Diagnostic &Diags = S.getDiagnostics();
353
354 // Short circuit for compilation speed.
355 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
356 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000357
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000358 // FIXME: Function try block
359 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
360 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000361 case UnknownFallThrough:
362 break;
363
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000364 case MaybeFallThrough:
365 if (HasNoReturn)
366 S.Diag(Compound->getRBracLoc(),
367 CD.diag_MaybeFallThrough_HasNoReturn);
368 else if (!ReturnsVoid)
369 S.Diag(Compound->getRBracLoc(),
370 CD.diag_MaybeFallThrough_ReturnsNonVoid);
371 break;
372 case AlwaysFallThrough:
373 if (HasNoReturn)
374 S.Diag(Compound->getRBracLoc(),
375 CD.diag_AlwaysFallThrough_HasNoReturn);
376 else if (!ReturnsVoid)
377 S.Diag(Compound->getRBracLoc(),
378 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
379 break;
380 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000381 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
382 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
383 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
384 << FD;
385 } else {
386 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
387 }
388 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000389 break;
390 case NeverFallThrough:
391 break;
392 }
393 }
394}
395
396//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000397// -Wuninitialized
398//===----------------------------------------------------------------------===//
399
Ted Kremenek6f417152011-04-04 20:56:00 +0000400namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000401/// ContainsReference - A visitor class to search for references to
402/// a particular declaration (the needle) within any evaluated component of an
403/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000404class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000405 bool FoundReference;
406 const DeclRefExpr *Needle;
407
Ted Kremenek6f417152011-04-04 20:56:00 +0000408public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000409 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
410 : EvaluatedExprVisitor<ContainsReference>(Context),
411 FoundReference(false), Needle(Needle) {}
412
413 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000414 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000415 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000416 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000417
418 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000419 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000420
421 void VisitDeclRefExpr(DeclRefExpr *E) {
422 if (E == Needle)
423 FoundReference = true;
424 else
425 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000426 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000427
428 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000429};
430}
431
Chandler Carruth262d50e2011-04-05 18:27:05 +0000432/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
433/// uninitialized variable. This manages the different forms of diagnostic
434/// emitted for particular types of uses. Returns true if the use was diagnosed
435/// as a warning. If a pariticular use is one we omit warnings for, returns
436/// false.
437static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Chandler Carruth64fb9592011-04-05 18:18:08 +0000438 const Expr *E, bool isAlwaysUninit) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000439 bool isSelfInit = false;
440
441 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
442 if (isAlwaysUninit) {
443 // Inspect the initializer of the variable declaration which is
444 // being referenced prior to its initialization. We emit
445 // specialized diagnostics for self-initialization, and we
446 // specifically avoid warning about self references which take the
447 // form of:
448 //
449 // int x = x;
450 //
451 // This is used to indicate to GCC that 'x' is intentionally left
452 // uninitialized. Proven code paths which access 'x' in
453 // an uninitialized state after this will still warn.
454 //
455 // TODO: Should we suppress maybe-uninitialized warnings for
456 // variables initialized in this way?
457 if (const Expr *Initializer = VD->getInit()) {
458 if (DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000459 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000460
461 ContainsReference CR(S.Context, DRE);
462 CR.Visit(const_cast<Expr*>(Initializer));
463 isSelfInit = CR.doesContainReference();
464 }
465 if (isSelfInit) {
466 S.Diag(DRE->getLocStart(),
467 diag::warn_uninit_self_reference_in_init)
468 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
469 } else {
470 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
471 << VD->getDeclName() << DRE->getSourceRange();
472 }
473 } else {
474 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
475 << VD->getDeclName() << DRE->getSourceRange();
476 }
477 } else {
478 const BlockExpr *BE = cast<BlockExpr>(E);
479 S.Diag(BE->getLocStart(),
480 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
481 : diag::warn_maybe_uninit_var_captured_by_block)
482 << VD->getDeclName();
483 }
484
485 // Report where the variable was declared when the use wasn't within
486 // the initializer of that declaration.
487 if (!isSelfInit)
488 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
489 << VD->getDeclName();
490
Chandler Carruth262d50e2011-04-05 18:27:05 +0000491 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000492}
493
Chandler Carruth262d50e2011-04-05 18:27:05 +0000494static void SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000495 // Don't issue a fixit if there is already an initializer.
496 if (VD->getInit())
497 return;
498
499 // Suggest possible initialization (if any).
500 const char *initialization = 0;
501 QualType VariableTy = VD->getType().getCanonicalType();
502
Douglas Gregor8ba44262011-07-02 00:59:18 +0000503 if (VariableTy->isObjCObjectPointerType() ||
504 VariableTy->isBlockPointerType()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000505 // Check if 'nil' is defined.
506 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
507 initialization = " = nil";
508 else
509 initialization = " = 0";
510 }
511 else if (VariableTy->isRealFloatingType())
512 initialization = " = 0.0";
513 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
514 initialization = " = false";
515 else if (VariableTy->isEnumeralType())
516 return;
Douglas Gregor8ba44262011-07-02 00:59:18 +0000517 else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType()) {
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000518 if (S.Context.getLangOptions().CPlusPlus0x)
519 initialization = " = nullptr";
Douglas Gregor8ba44262011-07-02 00:59:18 +0000520 // Check if 'NULL' is defined.
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000521 else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL")))
Douglas Gregor8ba44262011-07-02 00:59:18 +0000522 initialization = " = NULL";
523 else
524 initialization = " = 0";
525 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000526 else if (VariableTy->isScalarType())
527 initialization = " = 0";
528
529 if (initialization) {
530 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
531 S.Diag(loc, diag::note_var_fixit_add_initialization)
532 << FixItHint::CreateInsertion(loc, initialization);
533 }
534}
535
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000536typedef std::pair<const Expr*, bool> UninitUse;
537
Ted Kremenek610068c2011-01-15 02:58:47 +0000538namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000539struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000540 bool operator()(const UninitUse &a, const UninitUse &b) {
541 SourceLocation aLoc = a.first->getLocStart();
542 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000543 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
544 }
545};
546
Ted Kremenek610068c2011-01-15 02:58:47 +0000547class UninitValsDiagReporter : public UninitVariablesHandler {
548 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000549 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000550 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
551 UsesMap *uses;
552
Ted Kremenek610068c2011-01-15 02:58:47 +0000553public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000554 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
555 ~UninitValsDiagReporter() {
556 flushDiagnostics();
557 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000558
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000559 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
560 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000561 if (!uses)
562 uses = new UsesMap();
563
564 UsesVec *&vec = (*uses)[vd];
565 if (!vec)
566 vec = new UsesVec();
567
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000568 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000569 }
570
571 void flushDiagnostics() {
572 if (!uses)
573 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000574
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000575 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
576 const VarDecl *vd = i->first;
577 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000578
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000579 // Sort the uses by their SourceLocations. While not strictly
580 // guaranteed to produce them in line/column order, this will provide
581 // a stable ordering.
582 std::sort(vec->begin(), vec->end(), SLocSort());
583
Chandler Carruth64fb9592011-04-05 18:18:08 +0000584 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
585 ++vi) {
Chandler Carruth262d50e2011-04-05 18:27:05 +0000586 if (!DiagnoseUninitializedUse(S, vd, vi->first,
587 /*isAlwaysUninit=*/vi->second))
588 continue;
589
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000590 SuggestInitializationFixit(S, vd);
591
592 // Skip further diagnostics for this variable. We try to warn only on
593 // the first point at which a variable is used uninitialized.
594 break;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000595 }
Ted Kremenekd40066b2011-04-04 23:29:12 +0000596
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000597 delete vec;
598 }
599 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000600 }
601};
602}
603
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000604
605//===----------------------------------------------------------------------===//
606// -Wthread-safety
607//===----------------------------------------------------------------------===//
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000608namespace clang {
609namespace thread_safety {
610typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag;
611typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
612
613enum ProtectedOperationKind {
614 POK_VarDereference,
615 POK_VarAccess,
616 POK_FunctionCall
617};
618
619enum LockKind {
620 LK_Shared,
621 LK_Exclusive
622};
623
624enum AccessKind {
625 AK_Read,
626 AK_Written
627};
628
629
630struct SortDiagBySourceLocation {
631 Sema &S;
632 SortDiagBySourceLocation(Sema &S) : S(S) {}
633
634 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
635 // Although this call will be slow, this is only called when outputting
636 // multiple warnings.
637 return S.getSourceManager().isBeforeInTranslationUnit(left.first,
638 right.first);
639 }
640};
641
642/// \brief Helper function that returns a LockKind required for the given level
643/// of access.
644LockKind getLockKindFromAccessKind(AccessKind AK) {
645 switch (AK) {
646 case AK_Read :
647 return LK_Shared;
648 case AK_Written :
649 return LK_Exclusive;
650 }
651}
652
653class ThreadSafetyHandler {
654public:
655 typedef llvm::StringRef Name;
656 ThreadSafetyHandler() {}
657 virtual ~ThreadSafetyHandler() {}
658 virtual void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {}
659 virtual void handleDoubleLock(Name LockName, SourceLocation Loc) {}
660 virtual void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc){}
661 virtual void handleNoLockLoopEntry(Name LockName, SourceLocation Loc) {}
662 virtual void handleNoUnlock(Name LockName, Name FunName,
663 SourceLocation Loc) {}
664 virtual void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
665 SourceLocation Loc2) {}
666 virtual void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
667 AccessKind AK, SourceLocation Loc) {}
668 virtual void handleMutexNotHeld(const NamedDecl *D,
669 ProtectedOperationKind POK, Name LockName,
670 LockKind LK, SourceLocation Loc) {}
671 virtual void handleFunExcludesLock(Name FunName, Name LockName,
672 SourceLocation Loc) {}
673};
674
675class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
676 Sema &S;
677 DiagList Warnings;
678
679 // Helper functions
680 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
681 PartialDiagnostic Warning = S.PDiag(DiagID) << LockName;
682 Warnings.push_back(DelayedDiag(Loc, Warning));
683 }
684
685 public:
686 ThreadSafetyReporter(Sema &S) : S(S) {}
687
688 /// \brief Emit all buffered diagnostics in order of sourcelocation.
689 /// We need to output diagnostics produced while iterating through
690 /// the lockset in deterministic order, so this function orders diagnostics
691 /// and outputs them.
692 void emitDiagnostics() {
693 SortDiagBySourceLocation SortDiagBySL(S);
694 sort(Warnings.begin(), Warnings.end(), SortDiagBySL);
695 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
696 I != E; ++I)
697 S.Diag(I->first, I->second);
698 }
699
700 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
701 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
702 }
703
704 void handleDoubleLock(Name LockName, SourceLocation Loc) {
705 warnLockMismatch(diag::warn_double_lock, LockName, Loc);
706 }
707
708 void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc){
709 warnLockMismatch(diag::warn_lock_at_end_of_scope, LockName, Loc);
710 }
711
712 void handleNoLockLoopEntry(Name LockName, SourceLocation Loc) {
713 warnLockMismatch(diag::warn_expecting_lock_held_on_loop, LockName, Loc);
714 }
715
716 void handleNoUnlock(Name LockName, llvm::StringRef FunName,
717 SourceLocation Loc) {
718 PartialDiagnostic Warning =
719 S.PDiag(diag::warn_no_unlock) << LockName << FunName;
720 Warnings.push_back(DelayedDiag(Loc, Warning));
721 }
722
723 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
724 SourceLocation Loc2) {
725 PartialDiagnostic Warning =
726 S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName;
727 PartialDiagnostic Note =
728 S.PDiag(diag::note_lock_exclusive_and_shared) << LockName;
729 Warnings.push_back(DelayedDiag(Loc1, Warning));
730 Warnings.push_back(DelayedDiag(Loc2, Note));
731 }
732
733 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
734 AccessKind AK, SourceLocation Loc) {
735 unsigned DiagID;
736 switch (POK) {
737 case POK_VarAccess:
738 DiagID = diag::warn_variable_requires_any_lock;
739 break;
740 case POK_VarDereference:
741 DiagID = diag::warn_var_deref_requires_any_lock;
742 break;
743 default:
744 return;
745 break;
746 }
747 PartialDiagnostic Warning = S.PDiag(DiagID) << D->getName();
748 Warnings.push_back(DelayedDiag(Loc, Warning));
749 }
750
751 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
752 Name LockName, LockKind LK, SourceLocation Loc) {
753 unsigned DiagID;
754 switch (POK) {
755 case POK_VarAccess:
756 DiagID = diag::warn_variable_requires_lock;
757 break;
758 case POK_VarDereference:
759 DiagID = diag::warn_var_deref_requires_lock;
760 break;
761 case POK_FunctionCall:
762 DiagID = diag::warn_fun_requires_lock;
763 break;
764 }
765 PartialDiagnostic Warning = S.PDiag(DiagID)
766 << D->getName().str() << LockName << LK;
767 Warnings.push_back(DelayedDiag(Loc, Warning));
768 }
769
770 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
771 PartialDiagnostic Warning =
772 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName;
773 Warnings.push_back(DelayedDiag(Loc, Warning));
774 }
775};
776}
777}
778
779using namespace thread_safety;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000780
781namespace {
782/// \brief Implements a set of CFGBlocks using a BitVector.
783///
784/// This class contains a minimal interface, primarily dictated by the SetType
785/// template parameter of the llvm::po_iterator template, as used with external
786/// storage. We also use this set to keep track of which CFGBlocks we visit
787/// during the analysis.
788class CFGBlockSet {
789 llvm::BitVector VisitedBlockIDs;
790
791public:
792 // po_iterator requires this iterator, but the only interface needed is the
793 // value_type typedef.
794 struct iterator {
795 typedef const CFGBlock *value_type;
796 };
797
798 CFGBlockSet() {}
799 CFGBlockSet(const CFG *G) : VisitedBlockIDs(G->getNumBlockIDs(), false) {}
800
801 /// \brief Set the bit associated with a particular CFGBlock.
802 /// This is the important method for the SetType template parameter.
803 bool insert(const CFGBlock *Block) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +0000804 // Note that insert() is called by po_iterator, which doesn't check to make
805 // sure that Block is non-null. Moreover, the CFGBlock iterator will
806 // occasionally hand out null pointers for pruned edges, so we catch those
807 // here.
808 if (Block == 0)
809 return false; // if an edge is trivially false.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000810 if (VisitedBlockIDs.test(Block->getBlockID()))
811 return false;
812 VisitedBlockIDs.set(Block->getBlockID());
813 return true;
814 }
815
816 /// \brief Check if the bit for a CFGBlock has been already set.
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +0000817 /// This method is for tracking visited blocks in the main threadsafety loop.
818 /// Block must not be null.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000819 bool alreadySet(const CFGBlock *Block) {
820 return VisitedBlockIDs.test(Block->getBlockID());
821 }
822};
823
824/// \brief We create a helper class which we use to iterate through CFGBlocks in
825/// the topological order.
826class TopologicallySortedCFG {
827 typedef llvm::po_iterator<const CFG*, CFGBlockSet, true> po_iterator;
828
829 std::vector<const CFGBlock*> Blocks;
830
831public:
832 typedef std::vector<const CFGBlock*>::reverse_iterator iterator;
833
834 TopologicallySortedCFG(const CFG *CFGraph) {
835 Blocks.reserve(CFGraph->getNumBlockIDs());
836 CFGBlockSet BSet(CFGraph);
837
838 for (po_iterator I = po_iterator::begin(CFGraph, BSet),
839 E = po_iterator::end(CFGraph, BSet); I != E; ++I) {
840 Blocks.push_back(*I);
841 }
842 }
843
844 iterator begin() {
845 return Blocks.rbegin();
846 }
847
848 iterator end() {
849 return Blocks.rend();
850 }
851};
852
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000853/// \brief A MutexID object uniquely identifies a particular mutex, and
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000854/// is built from an Expr* (i.e. calling a lock function).
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000855///
856/// Thread-safety analysis works by comparing lock expressions. Within the
857/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000858/// a particular mutex object at run-time. Subsequent occurrences of the same
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000859/// expression (where "same" means syntactic equality) will refer to the same
860/// run-time object if three conditions hold:
861/// (1) Local variables in the expression, such as "x" have not changed.
862/// (2) Values on the heap that affect the expression have not changed.
863/// (3) The expression involves only pure function calls.
864/// The current implementation assumes, but does not verify, that multiple uses
865/// of the same lock expression satisfies these criteria.
866///
867/// Clang introduces an additional wrinkle, which is that it is difficult to
868/// derive canonical expressions, or compare expressions directly for equality.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000869/// Thus, we identify a mutex not by an Expr, but by the set of named
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000870/// declarations that are referenced by the Expr. In other words,
871/// x->foo->bar.mu will be a four element vector with the Decls for
872/// mu, bar, and foo, and x. The vector will uniquely identify the expression
873/// for all practical purposes.
874///
875/// Note we will need to perform substitution on "this" and function parameter
876/// names when constructing a lock expression.
877///
878/// For example:
879/// class C { Mutex Mu; void lock() EXCLUSIVE_LOCK_FUNCTION(this->Mu); };
880/// void myFunc(C *X) { ... X->lock() ... }
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000881/// The original expression for the mutex acquired by myFunc is "this->Mu", but
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000882/// "X" is substituted for "this" so we get X->Mu();
883///
884/// For another example:
885/// foo(MyList *L) EXCLUSIVE_LOCKS_REQUIRED(L->Mu) { ... }
886/// MyList *MyL;
887/// foo(MyL); // requires lock MyL->Mu to be held
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000888class MutexID {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000889 SmallVector<NamedDecl*, 2> DeclSeq;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000890
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000891 /// Build a Decl sequence representing the lock from the given expression.
892 /// Recursive function that bottoms out when the final DeclRefExpr is reached.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000893 void buildMutexID(Expr *Exp) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000894 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
895 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
896 DeclSeq.push_back(ND);
897 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
898 NamedDecl *ND = ME->getMemberDecl();
899 DeclSeq.push_back(ND);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000900 buildMutexID(ME->getBase());
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +0000901 } else if (isa<CXXThisExpr>(Exp)) {
902 return;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000903 } else {
904 // FIXME: add diagnostic
905 llvm::report_fatal_error("Expected lock expression!");
906 }
907 }
908
909public:
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000910 MutexID(Expr *LExpr) {
911 buildMutexID(LExpr);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000912 assert(!DeclSeq.empty());
913 }
914
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000915 bool operator==(const MutexID &other) const {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000916 return DeclSeq == other.DeclSeq;
917 }
918
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000919 bool operator!=(const MutexID &other) const {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000920 return !(*this == other);
921 }
922
923 // SmallVector overloads Operator< to do lexicographic ordering. Note that
924 // we use pointer equality (and <) to compare NamedDecls. This means the order
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000925 // of MutexIDs in a lockset is nondeterministic. In order to output
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000926 // diagnostics in a deterministic ordering, we must order all diagnostics to
927 // output by SourceLocation when iterating through this lockset.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000928 bool operator<(const MutexID &other) const {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000929 return DeclSeq < other.DeclSeq;
930 }
931
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000932 /// \brief Returns the name of the first Decl in the list for a given MutexID;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000933 /// e.g. the lock expression foo.bar() has name "bar".
934 /// The caret will point unambiguously to the lock expression, so using this
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000935 /// name in diagnostics is a way to get simple, and consistent, mutex names.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000936 /// We do not want to output the entire expression text for security reasons.
937 StringRef getName() const {
938 return DeclSeq.front()->getName();
939 }
940
941 void Profile(llvm::FoldingSetNodeID &ID) const {
942 for (SmallVectorImpl<NamedDecl*>::const_iterator I = DeclSeq.begin(),
943 E = DeclSeq.end(); I != E; ++I) {
944 ID.AddPointer(*I);
945 }
946 }
947};
948
949/// \brief This is a helper class that stores info about the most recent
950/// accquire of a Lock.
951///
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000952/// The main body of the analysis maps MutexIDs to LockDatas.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000953struct LockData {
954 SourceLocation AcquireLoc;
955
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000956 /// \brief LKind stores whether a lock is held shared or exclusively.
957 /// Note that this analysis does not currently support either re-entrant
958 /// locking or lock "upgrading" and "downgrading" between exclusive and
959 /// shared.
960 ///
961 /// FIXME: add support for re-entrant locking and lock up/downgrading
962 LockKind LKind;
963
964 LockData(SourceLocation AcquireLoc, LockKind LKind)
965 : AcquireLoc(AcquireLoc), LKind(LKind) {}
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000966
967 bool operator==(const LockData &other) const {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000968 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000969 }
970
971 bool operator!=(const LockData &other) const {
972 return !(*this == other);
973 }
974
975 void Profile(llvm::FoldingSetNodeID &ID) const {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000976 ID.AddInteger(AcquireLoc.getRawEncoding());
977 ID.AddInteger(LKind);
978 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000979};
980
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000981/// A Lockset maps each MutexID (defined above) to information about how it has
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000982/// been locked.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000983typedef llvm::ImmutableMap<MutexID, LockData> Lockset;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000984
985/// \brief We use this class to visit different types of expressions in
986/// CFGBlocks, and build up the lockset.
987/// An expression may cause us to add or remove locks from the lockset, or else
988/// output error messages related to missing locks.
989/// FIXME: In future, we may be able to not inherit from a visitor.
990class BuildLockset : public StmtVisitor<BuildLockset> {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +0000991 ThreadSafetyHandler &Handler;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000992 Lockset LSet;
993 Lockset::Factory &LocksetFactory;
994
995 // Helper functions
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000996 void removeLock(SourceLocation UnlockLoc, Expr *LockExp);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000997 void addLock(SourceLocation LockLoc, Expr *LockExp, LockKind LK);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000998 const ValueDecl *getValueDecl(Expr *Exp);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000999 void warnIfMutexNotHeld (const NamedDecl *D, Expr *Exp, AccessKind AK,
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001000 Expr *MutexExp, ProtectedOperationKind POK);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001001 void checkAccess(Expr *Exp, AccessKind AK);
1002 void checkDereference(Expr *Exp, AccessKind AK);
1003
1004 template <class AttrType>
1005 void addLocksToSet(LockKind LK, Attr *Attr, CXXMemberCallExpr *Exp);
1006
1007 /// \brief Returns true if the lockset contains a lock, regardless of whether
1008 /// the lock is held exclusively or shared.
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001009 bool locksetContains(MutexID Lock) const {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001010 return LSet.lookup(Lock);
1011 }
1012
1013 /// \brief Returns true if the lockset contains a lock with the passed in
1014 /// locktype.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001015 bool locksetContains(MutexID Lock, LockKind KindRequested) const {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001016 const LockData *LockHeld = LSet.lookup(Lock);
1017 return (LockHeld && KindRequested == LockHeld->LKind);
1018 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001019
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001020 /// \brief Returns true if the lockset contains a lock with at least the
1021 /// passed in locktype. So for example, if we pass in LK_Shared, this function
1022 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
1023 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
1024 bool locksetContainsAtLeast(MutexID Lock, LockKind KindRequested) const {
1025 switch (KindRequested) {
1026 case LK_Shared:
1027 return locksetContains(Lock);
1028 case LK_Exclusive:
1029 return locksetContains(Lock, KindRequested);
1030 }
1031 }
1032
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001033public:
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001034 BuildLockset(ThreadSafetyHandler &Handler, Lockset LS, Lockset::Factory &F)
1035 : StmtVisitor<BuildLockset>(), Handler(Handler), LSet(LS),
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001036 LocksetFactory(F) {}
1037
1038 Lockset getLockset() {
1039 return LSet;
1040 }
1041
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001042 void VisitUnaryOperator(UnaryOperator *UO);
1043 void VisitBinaryOperator(BinaryOperator *BO);
1044 void VisitCastExpr(CastExpr *CE);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001045 void VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp);
1046};
1047
1048/// \brief Add a new lock to the lockset, warning if the lock is already there.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001049/// \param LockLoc The source location of the acquire
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001050/// \param LockExp The lock expression corresponding to the lock to be added
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001051void BuildLockset::addLock(SourceLocation LockLoc, Expr *LockExp,
1052 LockKind LK) {
1053 // FIXME: deal with acquired before/after annotations
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001054 MutexID Mutex(LockExp);
1055 LockData NewLock(LockLoc, LK);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001056
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001057 // FIXME: Don't always warn when we have support for reentrant locks.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001058 if (locksetContains(Mutex))
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001059 Handler.handleDoubleLock(Mutex.getName(), LockLoc);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001060 LSet = LocksetFactory.add(LSet, Mutex, NewLock);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001061}
1062
1063/// \brief Remove a lock from the lockset, warning if the lock is not there.
1064/// \param LockExp The lock expression corresponding to the lock to be removed
1065/// \param UnlockLoc The source location of the unlock (only used in error msg)
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001066void BuildLockset::removeLock(SourceLocation UnlockLoc, Expr *LockExp) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001067 MutexID Mutex(LockExp);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001068
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001069 Lockset NewLSet = LocksetFactory.remove(LSet, Mutex);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001070 if(NewLSet == LSet)
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001071 Handler.handleUnmatchedUnlock(Mutex.getName(), UnlockLoc);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001072
1073 LSet = NewLSet;
1074}
1075
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001076/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1077const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1078 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1079 return DR->getDecl();
1080
1081 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1082 return ME->getMemberDecl();
1083
1084 return 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001085}
1086
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001087/// \brief Warn if the LSet does not contain a lock sufficient to protect access
1088/// of at least the passed in AccessType.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001089void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001090 AccessKind AK, Expr *MutexExp,
1091 ProtectedOperationKind POK) {
1092 LockKind LK = getLockKindFromAccessKind(AK);
1093 MutexID Mutex(MutexExp);
1094 if (!locksetContainsAtLeast(Mutex, LK))
1095 Handler.handleMutexNotHeld(D, POK, Mutex.getName(), LK, Exp->getExprLoc());
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001096}
1097
1098
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001099/// \brief This method identifies variable dereferences and checks pt_guarded_by
1100/// and pt_guarded_var annotations. Note that we only check these annotations
1101/// at the time a pointer is dereferenced.
1102/// FIXME: We need to check for other types of pointer dereferences
1103/// (e.g. [], ->) and deal with them here.
1104/// \param Exp An expression that has been read or written.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001105void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001106 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1107 if (!UO || UO->getOpcode() != clang::UO_Deref)
1108 return;
1109 Exp = UO->getSubExpr()->IgnoreParenCasts();
1110
1111 const ValueDecl *D = getValueDecl(Exp);
1112 if(!D || !D->hasAttrs())
1113 return;
1114
1115 if (D->getAttr<PtGuardedVarAttr>() && LSet.isEmpty())
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001116 Handler.handleNoMutexHeld(D, POK_VarDereference, AK, Exp->getExprLoc());
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001117
1118 const AttrVec &ArgAttrs = D->getAttrs();
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001119 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1120 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1121 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001122}
1123
1124/// \brief Checks guarded_by and guarded_var attributes.
1125/// Whenever we identify an access (read or write) of a DeclRefExpr or
1126/// MemberExpr, we need to check whether there are any guarded_by or
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001127/// guarded_var attributes, and make sure we hold the appropriate mutexes.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001128void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001129 const ValueDecl *D = getValueDecl(Exp);
1130 if(!D || !D->hasAttrs())
1131 return;
1132
1133 if (D->getAttr<GuardedVarAttr>() && LSet.isEmpty())
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001134 Handler.handleNoMutexHeld(D, POK_VarAccess, AK, Exp->getExprLoc());
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001135
1136 const AttrVec &ArgAttrs = D->getAttrs();
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001137 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1138 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1139 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001140}
1141
1142/// \brief For unary operations which read and write a variable, we need to
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001143/// check whether we hold any required mutexes. Reads are checked in
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001144/// VisitCastExpr.
1145void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1146 switch (UO->getOpcode()) {
1147 case clang::UO_PostDec:
1148 case clang::UO_PostInc:
1149 case clang::UO_PreDec:
1150 case clang::UO_PreInc: {
1151 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001152 checkAccess(SubExp, AK_Written);
1153 checkDereference(SubExp, AK_Written);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001154 break;
1155 }
1156 default:
1157 break;
1158 }
1159}
1160
1161/// For binary operations which assign to a variable (writes), we need to check
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001162/// whether we hold any required mutexes.
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001163/// FIXME: Deal with non-primitive types.
1164void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1165 if (!BO->isAssignmentOp())
1166 return;
1167 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001168 checkAccess(LHSExp, AK_Written);
1169 checkDereference(LHSExp, AK_Written);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001170}
1171
1172/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001173/// need to ensure we hold any required mutexes.
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001174/// FIXME: Deal with non-primitive types.
1175void BuildLockset::VisitCastExpr(CastExpr *CE) {
1176 if (CE->getCastKind() != CK_LValueToRValue)
1177 return;
1178 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001179 checkAccess(SubExp, AK_Read);
1180 checkDereference(SubExp, AK_Read);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001181}
1182
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001183/// \brief This function, parameterized by an attribute type, is used to add a
1184/// set of locks specified as attribute arguments to the lockset.
1185template <typename AttrType>
1186void BuildLockset::addLocksToSet(LockKind LK, Attr *Attr,
1187 CXXMemberCallExpr *Exp) {
1188 typedef typename AttrType::args_iterator iterator_type;
1189 SourceLocation ExpLocation = Exp->getExprLoc();
1190 Expr *Parent = Exp->getImplicitObjectArgument();
1191 AttrType *SpecificAttr = cast<AttrType>(Attr);
1192
1193 if (SpecificAttr->args_size() == 0) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001194 // The mutex held is the "this" object.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001195 addLock(ExpLocation, Parent, LK);
1196 return;
1197 }
1198
1199 for (iterator_type I = SpecificAttr->args_begin(),
1200 E = SpecificAttr->args_end(); I != E; ++I)
1201 addLock(ExpLocation, *I, LK);
1202}
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001203
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001204/// \brief When visiting CXXMemberCallExprs we need to examine the attributes on
1205/// the method that is being called and add, remove or check locks in the
1206/// lockset accordingly.
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001207///
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001208/// FIXME: For classes annotated with one of the guarded annotations, we need
1209/// to treat const method calls as reads and non-const method calls as writes,
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001210/// and check that the appropriate locks are held. Non-const method calls with
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001211/// the same signature as const method calls can be also treated as reads.
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001212///
1213/// FIXME: We need to also visit CallExprs to catch/check global functions.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001214void BuildLockset::VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001215 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1216
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001217 SourceLocation ExpLocation = Exp->getExprLoc();
1218 Expr *Parent = Exp->getImplicitObjectArgument();
1219
1220 if(!D || !D->hasAttrs())
1221 return;
1222
1223 AttrVec &ArgAttrs = D->getAttrs();
1224 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
1225 Attr *Attr = ArgAttrs[i];
1226 switch (Attr->getKind()) {
1227 // When we encounter an exclusive lock function, we need to add the lock
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001228 // to our lockset with kind exclusive.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001229 case attr::ExclusiveLockFunction:
1230 addLocksToSet<ExclusiveLockFunctionAttr>(LK_Exclusive, Attr, Exp);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001231 break;
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001232
1233 // When we encounter a shared lock function, we need to add the lock
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001234 // to our lockset with kind shared.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001235 case attr::SharedLockFunction:
1236 addLocksToSet<SharedLockFunctionAttr>(LK_Shared, Attr, Exp);
1237 break;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001238
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001239 // When we encounter an unlock function, we need to remove unlocked
1240 // mutexes from the lockset, and flag a warning if they are not there.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001241 case attr::UnlockFunction: {
1242 UnlockFunctionAttr *UFAttr = cast<UnlockFunctionAttr>(Attr);
1243
1244 if (UFAttr->args_size() == 0) { // The lock held is the "this" object.
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001245 removeLock(ExpLocation, Parent);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001246 break;
1247 }
1248
1249 for (UnlockFunctionAttr::args_iterator I = UFAttr->args_begin(),
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001250 E = UFAttr->args_end(); I != E; ++I)
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001251 removeLock(ExpLocation, *I);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001252 break;
1253 }
1254
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001255 case attr::ExclusiveLocksRequired: {
1256 // FIXME: Also use this attribute to add required locks to the initial
1257 // lockset when processing a CFG for a function annotated with this
1258 // attribute.
1259 ExclusiveLocksRequiredAttr *ELRAttr =
1260 cast<ExclusiveLocksRequiredAttr>(Attr);
1261
1262 for (ExclusiveLocksRequiredAttr::args_iterator
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001263 I = ELRAttr->args_begin(), E = ELRAttr->args_end(); I != E; ++I)
1264 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001265 break;
1266 }
1267
1268 case attr::SharedLocksRequired: {
1269 // FIXME: Also use this attribute to add required locks to the initial
1270 // lockset when processing a CFG for a function annotated with this
1271 // attribute.
1272 SharedLocksRequiredAttr *SLRAttr = cast<SharedLocksRequiredAttr>(Attr);
1273
1274 for (SharedLocksRequiredAttr::args_iterator I = SLRAttr->args_begin(),
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001275 E = SLRAttr->args_end(); I != E; ++I)
1276 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001277 break;
1278 }
1279
1280 case attr::LocksExcluded: {
1281 LocksExcludedAttr *LEAttr = cast<LocksExcludedAttr>(Attr);
1282 for (LocksExcludedAttr::args_iterator I = LEAttr->args_begin(),
1283 E = LEAttr->args_end(); I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001284 MutexID Mutex(*I);
1285 if (locksetContains(Mutex))
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001286 Handler.handleFunExcludesLock(D->getName(), Mutex.getName(),
1287 ExpLocation);
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001288 }
1289 break;
1290 }
1291
1292 case attr::LockReturned:
1293 // FIXME: Deal with this attribute.
1294 break;
1295
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001296 // Ignore other (non thread-safety) attributes
1297 default:
1298 break;
1299 }
1300 }
1301}
1302
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001303} // end anonymous namespace
1304
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001305/// \brief Flags a warning for each lock that is in LSet2 but not LSet1, or
1306/// else mutexes that are held shared in one lockset and exclusive in the other.
1307static Lockset warnIfNotInFirstSetOrNotSameKind(ThreadSafetyHandler &Handler,
1308 const Lockset LSet1,
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001309 const Lockset LSet2,
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001310 Lockset Intersection,
1311 Lockset::Factory &Fact) {
1312 for (Lockset::iterator I = LSet2.begin(), E = LSet2.end(); I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001313 const MutexID &LSet2Mutex = I.getKey();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001314 const LockData &LSet2LockData = I.getData();
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001315 if (const LockData *LD = LSet1.lookup(LSet2Mutex)) {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001316 if (LD->LKind != LSet2LockData.LKind) {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001317 Handler.handleExclusiveAndShared(LSet2Mutex.getName(),
1318 LSet2LockData.AcquireLoc,
1319 LD->AcquireLoc);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001320 if (LD->LKind != LK_Exclusive)
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001321 Intersection = Fact.add(Intersection, LSet2Mutex, LSet2LockData);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001322 }
1323 } else {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001324 Handler.handleMutexHeldEndOfScope(LSet2Mutex.getName(),
1325 LSet2LockData.AcquireLoc);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001326 }
1327 }
1328 return Intersection;
1329}
1330
1331
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001332/// \brief Compute the intersection of two locksets and issue warnings for any
1333/// locks in the symmetric difference.
1334///
1335/// This function is used at a merge point in the CFG when comparing the lockset
1336/// of each branch being merged. For example, given the following sequence:
1337/// A; if () then B; else C; D; we need to check that the lockset after B and C
1338/// are the same. In the event of a difference, we use the intersection of these
1339/// two locksets at the start of D.
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001340static Lockset intersectAndWarn(ThreadSafetyHandler &Handler,
1341 const Lockset LSet1, const Lockset LSet2,
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001342 Lockset::Factory &Fact) {
1343 Lockset Intersection = LSet1;
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001344 Intersection = warnIfNotInFirstSetOrNotSameKind(Handler, LSet1, LSet2,
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001345 Intersection, Fact);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001346
1347 for (Lockset::iterator I = LSet1.begin(), E = LSet1.end(); I != E; ++I) {
1348 if (!LSet2.contains(I.getKey())) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001349 const MutexID &Mutex = I.getKey();
1350 const LockData &MissingLock = I.getData();
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001351 Handler.handleMutexHeldEndOfScope(Mutex.getName(),
1352 MissingLock.AcquireLoc);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001353 Intersection = Fact.remove(Intersection, Mutex);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001354 }
1355 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001356 return Intersection;
1357}
1358
1359/// \brief Returns the location of the first Stmt in a Block.
1360static SourceLocation getFirstStmtLocation(CFGBlock *Block) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001361 SourceLocation Loc;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001362 for (CFGBlock::const_iterator BI = Block->begin(), BE = Block->end();
1363 BI != BE; ++BI) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001364 if (const CFGStmt *CfgStmt = dyn_cast<CFGStmt>(&(*BI))) {
1365 Loc = CfgStmt->getStmt()->getLocStart();
1366 if (Loc.isValid()) return Loc;
1367 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001368 }
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001369 if (Stmt *S = Block->getTerminator().getStmt()) {
1370 Loc = S->getLocStart();
1371 if (Loc.isValid()) return Loc;
1372 }
1373 return Loc;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001374}
1375
1376/// \brief Warn about different locksets along backedges of loops.
1377/// This function is called when we encounter a back edge. At that point,
1378/// we need to verify that the lockset before taking the backedge is the
1379/// same as the lockset before entering the loop.
1380///
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001381/// \param LoopEntrySet Locks before starting the loop
1382/// \param LoopReentrySet Locks in the last CFG block of the loop
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001383static void warnBackEdgeUnequalLocksets(ThreadSafetyHandler &Handler,
1384 const Lockset LoopReentrySet,
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001385 const Lockset LoopEntrySet,
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001386 SourceLocation FirstLocInLoop,
1387 Lockset::Factory &Fact) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001388 assert(FirstLocInLoop.isValid());
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001389 // Warn for locks held at the start of the loop, but not the end.
1390 for (Lockset::iterator I = LoopEntrySet.begin(), E = LoopEntrySet.end();
1391 I != E; ++I) {
1392 if (!LoopReentrySet.contains(I.getKey())) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001393 // We report this error at the location of the first statement in a loop
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001394 Handler.handleNoLockLoopEntry(I.getKey().getName(), FirstLocInLoop);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001395 }
1396 }
1397
1398 // Warn for locks held at the end of the loop, but not at the start.
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001399 warnIfNotInFirstSetOrNotSameKind(Handler, LoopEntrySet, LoopReentrySet,
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001400 LoopReentrySet, Fact);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001401}
1402
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001403
1404namespace clang { namespace thread_safety {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001405/// \brief Check a function's CFG for thread-safety violations.
1406///
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001407/// We traverse the blocks in the CFG, compute the set of mutexes that are held
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001408/// at the end of each block, and issue warnings for thread safety violations.
1409/// Each block in the CFG is traversed exactly once.
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001410void runThreadSafetyAnalysis(AnalysisContext &AC,
1411 ThreadSafetyHandler &Handler) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001412 CFG *CFGraph = AC.getCFG();
1413 if (!CFGraph) return;
Caitlin Sadowskiaf370612011-09-08 18:35:21 +00001414 const Decl *D = AC.getDecl();
1415 if (D && D->getAttr<NoThreadSafetyAnalysisAttr>()) return;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001416
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001417 Lockset::Factory LocksetFactory;
1418
1419 // FIXME: Swith to SmallVector? Otherwise improve performance impact?
1420 std::vector<Lockset> EntryLocksets(CFGraph->getNumBlockIDs(),
1421 LocksetFactory.getEmptyMap());
1422 std::vector<Lockset> ExitLocksets(CFGraph->getNumBlockIDs(),
1423 LocksetFactory.getEmptyMap());
1424
1425 // We need to explore the CFG via a "topological" ordering.
1426 // That way, we will be guaranteed to have information about required
1427 // predecessor locksets when exploring a new block.
1428 TopologicallySortedCFG SortedGraph(CFGraph);
1429 CFGBlockSet VisitedBlocks(CFGraph);
1430
1431 for (TopologicallySortedCFG::iterator I = SortedGraph.begin(),
1432 E = SortedGraph.end(); I!= E; ++I) {
1433 const CFGBlock *CurrBlock = *I;
1434 int CurrBlockID = CurrBlock->getBlockID();
1435
1436 VisitedBlocks.insert(CurrBlock);
1437
1438 // Use the default initial lockset in case there are no predecessors.
1439 Lockset &Entryset = EntryLocksets[CurrBlockID];
1440 Lockset &Exitset = ExitLocksets[CurrBlockID];
1441
1442 // Iterate through the predecessor blocks and warn if the lockset for all
1443 // predecessors is not the same. We take the entry lockset of the current
1444 // block to be the intersection of all previous locksets.
1445 // FIXME: By keeping the intersection, we may output more errors in future
1446 // for a lock which is not in the intersection, but was in the union. We
1447 // may want to also keep the union in future. As an example, let's say
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001448 // the intersection contains Mutex L, and the union contains L and M.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001449 // Later we unlock M. At this point, we would output an error because we
1450 // never locked M; although the real error is probably that we forgot to
1451 // lock M on all code paths. Conversely, let's say that later we lock M.
1452 // In this case, we should compare against the intersection instead of the
1453 // union because the real error is probably that we forgot to unlock M on
1454 // all code paths.
1455 bool LocksetInitialized = false;
1456 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1457 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1458
1459 // if *PI -> CurrBlock is a back edge
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001460 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001461 continue;
1462
1463 int PrevBlockID = (*PI)->getBlockID();
1464 if (!LocksetInitialized) {
1465 Entryset = ExitLocksets[PrevBlockID];
1466 LocksetInitialized = true;
1467 } else {
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001468 Entryset = intersectAndWarn(Handler, Entryset,
1469 ExitLocksets[PrevBlockID], LocksetFactory);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001470 }
1471 }
1472
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001473 BuildLockset LocksetBuilder(Handler, Entryset, LocksetFactory);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001474 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1475 BE = CurrBlock->end(); BI != BE; ++BI) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001476 if (const CFGStmt *CfgStmt = dyn_cast<CFGStmt>(&*BI))
Ted Kremenekf1d10d92011-08-23 23:05:04 +00001477 LocksetBuilder.Visit(const_cast<Stmt*>(CfgStmt->getStmt()));
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001478 }
1479 Exitset = LocksetBuilder.getLockset();
1480
1481 // For every back edge from CurrBlock (the end of the loop) to another block
1482 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
1483 // the one held at the beginning of FirstLoopBlock. We can look up the
1484 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
1485 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1486 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1487
1488 // if CurrBlock -> *SI is *not* a back edge
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001489 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001490 continue;
1491
1492 CFGBlock *FirstLoopBlock = *SI;
1493 SourceLocation FirstLoopLocation = getFirstStmtLocation(FirstLoopBlock);
1494
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001495 assert(FirstLoopLocation.isValid());
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001496
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001497 // Fail gracefully in release code.
1498 if (!FirstLoopLocation.isValid())
1499 continue;
1500
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001501 Lockset PreLoop = EntryLocksets[FirstLoopBlock->getBlockID()];
1502 Lockset LoopEnd = ExitLocksets[CurrBlockID];
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001503 warnBackEdgeUnequalLocksets(Handler, LoopEnd, PreLoop, FirstLoopLocation,
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001504 LocksetFactory);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001505 }
1506 }
1507
1508 Lockset FinalLockset = ExitLocksets[CFGraph->getExit().getBlockID()];
1509 if (!FinalLockset.isEmpty()) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001510 for (Lockset::iterator I=FinalLockset.begin(), E=FinalLockset.end();
1511 I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001512 const MutexID &Mutex = I.getKey();
1513 const LockData &MissingLock = I.getData();
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001514
1515 std::string FunName = "<unknown>";
1516 if (const NamedDecl *ContextDecl = dyn_cast<NamedDecl>(AC.getDecl())) {
1517 FunName = ContextDecl->getDeclName().getAsString();
1518 }
1519
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001520 Handler.handleNoUnlock(Mutex.getName(), FunName, MissingLock.AcquireLoc);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001521 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001522 }
1523}
1524
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001525}} // end namespace clang::thread_safety
1526
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001527
Ted Kremenek610068c2011-01-15 02:58:47 +00001528//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001529// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1530// warnings on a function, method, or block.
1531//===----------------------------------------------------------------------===//
1532
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001533clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1534 enableCheckFallThrough = 1;
1535 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001536 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001537}
1538
Chandler Carruth5d989942011-07-06 16:21:37 +00001539clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1540 : S(s),
1541 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001542 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001543 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001544 MaxCFGBlocksPerFunction(0),
1545 NumUninitAnalysisFunctions(0),
1546 NumUninitAnalysisVariables(0),
1547 MaxUninitAnalysisVariablesPerFunction(0),
1548 NumUninitAnalysisBlockVisits(0),
1549 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001550 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001551 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001552 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
1553 Diagnostic::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001554 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1555 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
1556 Diagnostic::Ignored);
1557
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001558}
1559
Ted Kremenek351ba912011-02-23 01:52:04 +00001560static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001561 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001562 i = fscope->PossiblyUnreachableDiags.begin(),
1563 e = fscope->PossiblyUnreachableDiags.end();
1564 i != e; ++i) {
1565 const sema::PossiblyUnreachableDiag &D = *i;
1566 S.Diag(D.Loc, D.PD);
1567 }
1568}
1569
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001570void clang::sema::
1571AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001572 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001573 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001574
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001575 // We avoid doing analysis-based warnings when there are errors for
1576 // two reasons:
1577 // (1) The CFGs often can't be constructed (if the body is invalid), so
1578 // don't bother trying.
1579 // (2) The code already has problems; running the analysis just takes more
1580 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +00001581 Diagnostic &Diags = S.getDiagnostics();
1582
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001583 // Do not do any analysis for declarations in system headers if we are
1584 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001585 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001586 S.SourceMgr.isInSystemHeader(D->getLocation()))
1587 return;
1588
John McCalle0054f62010-08-25 05:56:39 +00001589 // For code in dependent contexts, we'll do this at instantiation time.
1590 if (cast<DeclContext>(D)->isDependentContext())
1591 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001592
Ted Kremenek351ba912011-02-23 01:52:04 +00001593 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1594 // Flush out any possibly unreachable diagnostics.
1595 flushDiagnostics(S, fscope);
1596 return;
1597 }
1598
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001599 const Stmt *Body = D->getBody();
1600 assert(Body);
1601
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001602 AnalysisContext AC(D, 0);
1603
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001604 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1605 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001606 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1607 AC.getCFGBuildOptions().AddEHEdges = false;
1608 AC.getCFGBuildOptions().AddInitializers = true;
1609 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001610
1611 // Force that certain expressions appear as CFGElements in the CFG. This
1612 // is used to speed up various analyses.
1613 // FIXME: This isn't the right factoring. This is here for initial
1614 // prototyping, but we need a way for analyses to say what expressions they
1615 // expect to always be CFGElements and then fill in the BuildOptions
1616 // appropriately. This is essentially a layering violation.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001617 if (P.enableCheckUnreachable) {
1618 // Unreachable code analysis requires a linearized CFG.
1619 AC.getCFGBuildOptions().setAllAlwaysAdd();
1620 }
1621 else {
1622 AC.getCFGBuildOptions()
1623 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1624 .setAlwaysAdd(Stmt::BlockExprClass)
1625 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1626 .setAlwaysAdd(Stmt::DeclRefExprClass)
1627 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1628 .setAlwaysAdd(Stmt::UnaryOperatorClass);
1629 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001630
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001631 // Construct the analysis context with the specified CFG build options.
1632
Ted Kremenek351ba912011-02-23 01:52:04 +00001633 // Emit delayed diagnostics.
1634 if (!fscope->PossiblyUnreachableDiags.empty()) {
1635 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001636
1637 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001638 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001639 i = fscope->PossiblyUnreachableDiags.begin(),
1640 e = fscope->PossiblyUnreachableDiags.end();
1641 i != e; ++i) {
1642 if (const Stmt *stmt = i->stmt)
1643 AC.registerForcedBlockExpression(stmt);
1644 }
1645
1646 if (AC.getCFG()) {
1647 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001648 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001649 i = fscope->PossiblyUnreachableDiags.begin(),
1650 e = fscope->PossiblyUnreachableDiags.end();
1651 i != e; ++i)
1652 {
1653 const sema::PossiblyUnreachableDiag &D = *i;
1654 bool processed = false;
1655 if (const Stmt *stmt = i->stmt) {
1656 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
1657 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +00001658 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001659 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001660 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001661 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001662 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001663 }
1664 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001665 if (!processed) {
1666 // Emit the warning anyway if we cannot map to a basic block.
1667 S.Diag(D.Loc, D.PD);
1668 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001669 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001670 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001671
1672 if (!analyzed)
1673 flushDiagnostics(S, fscope);
1674 }
1675
1676
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001677 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001678 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001679 const CheckFallThroughDiagnostics &CD =
1680 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +00001681 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001682 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001683 }
1684
1685 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +00001686 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001687 CheckUnreachable(S, AC);
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001688
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001689 // Check for thread safety violations
Caitlin Sadowski75f23ae2011-09-09 16:04:02 +00001690 if (P.enableThreadSafetyAnalysis) {
1691 thread_safety::ThreadSafetyReporter Reporter(S);
1692 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1693 Reporter.emitDiagnostics();
1694 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001695
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001696 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +00001697 != Diagnostic::Ignored ||
1698 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +00001699 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001700 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001701 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001702 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001703 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001704 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001705 reporter, stats);
1706
1707 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1708 ++NumUninitAnalysisFunctions;
1709 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1710 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1711 MaxUninitAnalysisVariablesPerFunction =
1712 std::max(MaxUninitAnalysisVariablesPerFunction,
1713 stats.NumVariablesAnalyzed);
1714 MaxUninitAnalysisBlockVisitsPerFunction =
1715 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1716 stats.NumBlockVisits);
1717 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001718 }
1719 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001720
1721 // Collect statistics about the CFG if it was built.
1722 if (S.CollectStats && AC.isCFGBuilt()) {
1723 ++NumFunctionsAnalyzed;
1724 if (CFG *cfg = AC.getCFG()) {
1725 // If we successfully built a CFG for this context, record some more
1726 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001727 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001728 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001729 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001730 } else {
1731 ++NumFunctionsWithBadCFGs;
1732 }
1733 }
1734}
1735
1736void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1737 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1738
1739 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1740 unsigned AvgCFGBlocksPerFunction =
1741 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1742 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1743 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1744 << " " << NumCFGBlocks << " CFG blocks built.\n"
1745 << " " << AvgCFGBlocksPerFunction
1746 << " average CFG blocks per function.\n"
1747 << " " << MaxCFGBlocksPerFunction
1748 << " max CFG blocks per function.\n";
1749
1750 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1751 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1752 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1753 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1754 llvm::errs() << NumUninitAnalysisFunctions
1755 << " functions analyzed for uninitialiazed variables\n"
1756 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1757 << " " << AvgUninitVariablesPerFunction
1758 << " average variables per function.\n"
1759 << " " << MaxUninitAnalysisVariablesPerFunction
1760 << " max variables per function.\n"
1761 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1762 << " " << AvgUninitBlockVisitsPerFunction
1763 << " average block visits per function.\n"
1764 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1765 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001766}