blob: b89a83c8817d240eb979297d1118fa28d50a0e25 [file] [log] [blame]
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001//===- ThreadSafety.cpp ----------------------------------------*- 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// A intra-procedural analysis for thread safety (e.g. deadlocks and race
11// conditions), based off of an annotation system.
12//
Caitlin Sadowski19903462011-09-14 20:05:09 +000013// See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
14// information.
Caitlin Sadowski402aa062011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek439ed162011-10-22 02:14:27 +000019#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000020#include "clang/Analysis/AnalysisContext.h"
21#include "clang/Analysis/CFG.h"
22#include "clang/Analysis/CFGStmtMap.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000023#include "clang/AST/DeclCXX.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtVisitor.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceLocation.h"
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +000029#include "clang/Basic/OperatorKinds.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000030#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/ImmutableMap.h"
33#include "llvm/ADT/PostOrderIterator.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringRef.h"
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000036#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000037#include <algorithm>
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000038#include <utility>
Caitlin Sadowski402aa062011-09-09 16:11:56 +000039#include <vector>
40
41using namespace clang;
42using namespace thread_safety;
43
Caitlin Sadowski19903462011-09-14 20:05:09 +000044// Key method definition
45ThreadSafetyHandler::~ThreadSafetyHandler() {}
46
Caitlin Sadowski402aa062011-09-09 16:11:56 +000047namespace {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +000048
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000049/// SExpr implements a simple expression language that is used to store,
50/// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
51/// does not capture surface syntax, and it does not distinguish between
52/// C++ concepts, like pointers and references, that have no real semantic
53/// differences. This simplicity allows SExprs to be meaningfully compared,
54/// e.g.
55/// (x) = x
56/// (*this).foo = this->foo
57/// *&a = a
Caitlin Sadowski402aa062011-09-09 16:11:56 +000058///
59/// Thread-safety analysis works by comparing lock expressions. Within the
60/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
61/// a particular mutex object at run-time. Subsequent occurrences of the same
62/// expression (where "same" means syntactic equality) will refer to the same
63/// run-time object if three conditions hold:
64/// (1) Local variables in the expression, such as "x" have not changed.
65/// (2) Values on the heap that affect the expression have not changed.
66/// (3) The expression involves only pure function calls.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +000067///
Caitlin Sadowski402aa062011-09-09 16:11:56 +000068/// The current implementation assumes, but does not verify, that multiple uses
69/// of the same lock expression satisfies these criteria.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000070class SExpr {
71private:
72 enum ExprOp {
Ted Kremenekad0fe032012-08-22 23:50:41 +000073 EOP_Nop, ///< No-op
74 EOP_Wildcard, ///< Matches anything.
75 EOP_This, ///< This keyword.
76 EOP_NVar, ///< Named variable.
77 EOP_LVar, ///< Local variable.
78 EOP_Dot, ///< Field access
79 EOP_Call, ///< Function call
80 EOP_MCall, ///< Method call
81 EOP_Index, ///< Array index
82 EOP_Unary, ///< Unary operation
83 EOP_Binary, ///< Binary operation
84 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000085 };
86
87
88 class SExprNode {
89 private:
Ted Kremenekad0fe032012-08-22 23:50:41 +000090 unsigned char Op; ///< Opcode of the root node
91 unsigned char Flags; ///< Additional opcode-specific data
92 unsigned short Sz; ///< Number of child nodes
93 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000094
95 public:
96 SExprNode(ExprOp O, unsigned F, const void* D)
97 : Op(static_cast<unsigned char>(O)),
98 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
99 { }
100
101 unsigned size() const { return Sz; }
102 void setSize(unsigned S) { Sz = S; }
103
104 ExprOp kind() const { return static_cast<ExprOp>(Op); }
105
106 const NamedDecl* getNamedDecl() const {
107 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
108 return reinterpret_cast<const NamedDecl*>(Data);
109 }
110
111 const NamedDecl* getFunctionDecl() const {
112 assert(Op == EOP_Call || Op == EOP_MCall);
113 return reinterpret_cast<const NamedDecl*>(Data);
114 }
115
116 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
117 void setArrow(bool A) { Flags = A ? 1 : 0; }
118
119 unsigned arity() const {
120 switch (Op) {
121 case EOP_Nop: return 0;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000122 case EOP_Wildcard: return 0;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000123 case EOP_NVar: return 0;
124 case EOP_LVar: return 0;
125 case EOP_This: return 0;
126 case EOP_Dot: return 1;
127 case EOP_Call: return Flags+1; // First arg is function.
128 case EOP_MCall: return Flags+1; // First arg is implicit obj.
129 case EOP_Index: return 2;
130 case EOP_Unary: return 1;
131 case EOP_Binary: return 2;
132 case EOP_Unknown: return Flags;
133 }
134 return 0;
135 }
136
137 bool operator==(const SExprNode& Other) const {
138 // Ignore flags and size -- they don't matter.
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000139 return (Op == Other.Op &&
140 Data == Other.Data);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000141 }
142
143 bool operator!=(const SExprNode& Other) const {
144 return !(*this == Other);
145 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000146
147 bool matches(const SExprNode& Other) const {
148 return (*this == Other) ||
149 (Op == EOP_Wildcard) ||
150 (Other.Op == EOP_Wildcard);
151 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000152 };
153
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000154
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000155 /// \brief Encapsulates the lexical context of a function call. The lexical
156 /// context includes the arguments to the call, including the implicit object
157 /// argument. When an attribute containing a mutex expression is attached to
158 /// a method, the expression may refer to formal parameters of the method.
159 /// Actual arguments must be substituted for formal parameters to derive
160 /// the appropriate mutex expression in the lexical context where the function
161 /// is called. PrevCtx holds the context in which the arguments themselves
162 /// should be evaluated; multiple calling contexts can be chained together
163 /// by the lock_returned attribute.
164 struct CallingContext {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000165 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
166 Expr* SelfArg; // Implicit object argument -- e.g. 'this'
167 bool SelfArrow; // is Self referred to with -> or .?
168 unsigned NumArgs; // Number of funArgs
169 Expr** FunArgs; // Function arguments
170 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000171
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000172 CallingContext(const NamedDecl *D = 0, Expr *S = 0,
173 unsigned N = 0, Expr **A = 0, CallingContext *P = 0)
174 : AttrDecl(D), SelfArg(S), SelfArrow(false),
175 NumArgs(N), FunArgs(A), PrevCtx(P)
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000176 { }
177 };
178
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000179 typedef SmallVector<SExprNode, 4> NodeVector;
180
181private:
182 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
183 // the list to be traversed as a tree.
184 NodeVector NodeVec;
185
186private:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000187 unsigned makeNop() {
188 NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
189 return NodeVec.size()-1;
190 }
191
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000192 unsigned makeWildcard() {
193 NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
194 return NodeVec.size()-1;
195 }
196
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000197 unsigned makeNamedVar(const NamedDecl *D) {
198 NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
199 return NodeVec.size()-1;
200 }
201
202 unsigned makeLocalVar(const NamedDecl *D) {
203 NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
204 return NodeVec.size()-1;
205 }
206
207 unsigned makeThis() {
208 NodeVec.push_back(SExprNode(EOP_This, 0, 0));
209 return NodeVec.size()-1;
210 }
211
212 unsigned makeDot(const NamedDecl *D, bool Arrow) {
213 NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
214 return NodeVec.size()-1;
215 }
216
217 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
218 NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
219 return NodeVec.size()-1;
220 }
221
222 unsigned makeMCall(unsigned NumArgs, const NamedDecl *D) {
223 NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, D));
224 return NodeVec.size()-1;
225 }
226
227 unsigned makeIndex() {
228 NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
229 return NodeVec.size()-1;
230 }
231
232 unsigned makeUnary() {
233 NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
234 return NodeVec.size()-1;
235 }
236
237 unsigned makeBinary() {
238 NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
239 return NodeVec.size()-1;
240 }
241
242 unsigned makeUnknown(unsigned Arity) {
243 NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
244 return NodeVec.size()-1;
245 }
246
247 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000248 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000249 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000250 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000251 ///
252 /// NDeref returns the number of Derefence and AddressOf operations
253 /// preceeding the Expr; this is used to decide whether to pretty-print
254 /// SExprs with . or ->.
255 unsigned buildSExpr(Expr *Exp, CallingContext* CallCtx, int* NDeref = 0) {
256 if (!Exp)
257 return 0;
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000258
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000259 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
260 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000261 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
262 if (PV) {
263 FunctionDecl *FD =
264 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
265 unsigned i = PV->getFunctionScopeIndex();
266
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000267 if (CallCtx && CallCtx->FunArgs &&
268 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000269 // Substitute call arguments for references to function parameters
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000270 assert(i < CallCtx->NumArgs);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000271 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000272 }
273 // Map the param back to the param of the original function declaration.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000274 makeNamedVar(FD->getParamDecl(i));
275 return 1;
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000276 }
277 // Not a function parameter -- just store the reference.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000278 makeNamedVar(ND);
279 return 1;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000280 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000281 // Substitute parent for 'this'
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000282 if (CallCtx && CallCtx->SelfArg) {
283 if (!CallCtx->SelfArrow && NDeref)
284 // 'this' is a pointer, but self is not, so need to take address.
285 --(*NDeref);
286 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
287 }
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000288 else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000289 makeThis();
290 return 1;
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000291 }
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000292 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
293 NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000294 int ImplicitDeref = ME->isArrow() ? 1 : 0;
295 unsigned Root = makeDot(ND, false);
296 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
297 NodeVec[Root].setArrow(ImplicitDeref > 0);
298 NodeVec[Root].setSize(Sz + 1);
299 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000300 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000301 // When calling a function with a lock_returned attribute, replace
302 // the function call with the expression in lock_returned.
DeLesley Hutchins54081532012-08-31 22:09:53 +0000303 CXXMethodDecl* MD =
304 cast<CXXMethodDecl>(CMCE->getMethodDecl()->getMostRecentDecl());
305 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000306 CallingContext LRCallCtx(CMCE->getMethodDecl());
307 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000308 LRCallCtx.SelfArrow =
309 dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000310 LRCallCtx.NumArgs = CMCE->getNumArgs();
311 LRCallCtx.FunArgs = CMCE->getArgs();
312 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000313 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000314 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000315 // Hack to treat smart pointers and iterators as pointers;
316 // ignore any method named get().
317 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
318 CMCE->getNumArgs() == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000319 if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
320 ++(*NDeref);
321 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000322 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000323 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000324 unsigned Root =
325 makeMCall(NumCallArgs, CMCE->getMethodDecl()->getCanonicalDecl());
326 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000327 Expr** CallArgs = CMCE->getArgs();
328 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000329 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000330 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000331 NodeVec[Root].setSize(Sz + 1);
332 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000333 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
DeLesley Hutchins54081532012-08-31 22:09:53 +0000334 FunctionDecl* FD =
335 cast<FunctionDecl>(CE->getDirectCallee()->getMostRecentDecl());
336 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000337 CallingContext LRCallCtx(CE->getDirectCallee());
338 LRCallCtx.NumArgs = CE->getNumArgs();
339 LRCallCtx.FunArgs = CE->getArgs();
340 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000341 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000342 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000343 // Treat smart pointers and iterators as pointers;
344 // ignore the * and -> operators.
345 if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
346 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000347 if (k == OO_Star) {
348 if (NDeref) ++(*NDeref);
349 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
350 }
351 else if (k == OO_Arrow) {
352 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000353 }
354 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000355 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000356 unsigned Root = makeCall(NumCallArgs, 0);
357 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000358 Expr** CallArgs = CE->getArgs();
359 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000360 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000361 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000362 NodeVec[Root].setSize(Sz+1);
363 return Sz+1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000364 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000365 unsigned Root = makeBinary();
366 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
367 Sz += buildSExpr(BOE->getRHS(), CallCtx);
368 NodeVec[Root].setSize(Sz);
369 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000370 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000371 // Ignore & and * operators -- they're no-ops.
372 // However, we try to figure out whether the expression is a pointer,
373 // so we can use . and -> appropriately in error messages.
374 if (UOE->getOpcode() == UO_Deref) {
375 if (NDeref) ++(*NDeref);
376 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
377 }
378 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000379 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
380 if (DRE->getDecl()->isCXXInstanceMember()) {
381 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
382 // We interpret this syntax specially, as a wildcard.
383 unsigned Root = makeDot(DRE->getDecl(), false);
384 makeWildcard();
385 NodeVec[Root].setSize(2);
386 return 2;
387 }
388 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000389 if (NDeref) --(*NDeref);
390 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
391 }
392 unsigned Root = makeUnary();
393 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
394 NodeVec[Root].setSize(Sz);
395 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000396 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000397 unsigned Root = makeIndex();
398 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
399 Sz += buildSExpr(ASE->getIdx(), CallCtx);
400 NodeVec[Root].setSize(Sz);
401 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000402 } else if (AbstractConditionalOperator *CE =
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000403 dyn_cast<AbstractConditionalOperator>(Exp)) {
404 unsigned Root = makeUnknown(3);
405 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
406 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
407 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
408 NodeVec[Root].setSize(Sz);
409 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000410 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000411 unsigned Root = makeUnknown(3);
412 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
413 Sz += buildSExpr(CE->getLHS(), CallCtx);
414 Sz += buildSExpr(CE->getRHS(), CallCtx);
415 NodeVec[Root].setSize(Sz);
416 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000417 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000418 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000419 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000420 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000421 } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000422 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000423 } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000424 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000425 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000426 isa<CXXNullPtrLiteralExpr>(Exp) ||
427 isa<GNUNullExpr>(Exp) ||
428 isa<CXXBoolLiteralExpr>(Exp) ||
429 isa<FloatingLiteral>(Exp) ||
430 isa<ImaginaryLiteral>(Exp) ||
431 isa<IntegerLiteral>(Exp) ||
432 isa<StringLiteral>(Exp) ||
433 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000434 makeNop();
435 return 1; // FIXME: Ignore literals for now
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000436 } else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000437 makeNop();
438 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000439 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000440 }
441
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000442 /// \brief Construct a SExpr from an expression.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000443 /// \param MutexExp The original mutex expression within an attribute
444 /// \param DeclExp An expression involving the Decl on which the attribute
445 /// occurs.
446 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000447 void buildSExprFromExpr(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000448 CallingContext CallCtx(D);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000449
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000450 // Ignore string literals
451 if (MutexExp && isa<StringLiteral>(MutexExp)) {
452 makeNop();
453 return;
454 }
455
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000456 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000457 if (DeclExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000458 buildSExpr(MutexExp, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000459 return;
460 }
461
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000462 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000463 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000464 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000465 CallCtx.SelfArg = ME->getBase();
466 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000467 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000468 CallCtx.SelfArg = CE->getImplicitObjectArgument();
469 CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
470 CallCtx.NumArgs = CE->getNumArgs();
471 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsdf497822011-12-29 00:56:48 +0000472 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000473 CallCtx.NumArgs = CE->getNumArgs();
474 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000475 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000476 CallCtx.SelfArg = 0; // FIXME -- get the parent from DeclStmt
477 CallCtx.NumArgs = CE->getNumArgs();
478 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins6db51f72011-10-21 20:51:27 +0000479 } else if (D && isa<CXXDestructorDecl>(D)) {
480 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000481 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000482 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000483
484 // If the attribute has no arguments, then assume the argument is "this".
485 if (MutexExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000486 buildSExpr(CallCtx.SelfArg, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000487 return;
488 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000489
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000490 // For most attributes.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000491 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000492 }
493
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000494 /// \brief Get index of next sibling of node i.
495 unsigned getNextSibling(unsigned i) const {
496 return i + NodeVec[i].size();
497 }
498
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000499public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000500 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000501
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000502 /// \param MutexExp The original mutex expression within an attribute
503 /// \param DeclExp An expression involving the Decl on which the attribute
504 /// occurs.
505 /// \param D The declaration to which the lock/unlock attribute is attached.
506 /// Caller must check isValid() after construction.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000507 SExpr(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
508 buildSExprFromExpr(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000509 }
510
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000511 /// Return true if this is a valid decl sequence.
512 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000513 bool isValid() const {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000514 return !NodeVec.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000515 }
516
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000517 bool shouldIgnore() const {
518 // Nop is a mutex that we have decided to deliberately ignore.
519 assert(NodeVec.size() > 0 && "Invalid Mutex");
520 return NodeVec[0].kind() == EOP_Nop;
521 }
522
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000523 /// Issue a warning about an invalid lock expression
524 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
525 Expr *DeclExp, const NamedDecl* D) {
526 SourceLocation Loc;
527 if (DeclExp)
528 Loc = DeclExp->getExprLoc();
529
530 // FIXME: add a note about the attribute location in MutexExp or D
531 if (Loc.isValid())
532 Handler.handleInvalidLockExp(Loc);
533 }
534
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000535 bool operator==(const SExpr &other) const {
536 return NodeVec == other.NodeVec;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000537 }
538
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000539 bool operator!=(const SExpr &other) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000540 return !(*this == other);
541 }
542
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000543 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
544 if (NodeVec[i].matches(Other.NodeVec[j])) {
545 unsigned n = NodeVec[i].arity();
546 bool Result = true;
547 unsigned ci = i+1; // first child of i
548 unsigned cj = j+1; // first child of j
549 for (unsigned k = 0; k < n;
550 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
551 Result = Result && matches(Other, ci, cj);
552 }
553 return Result;
554 }
555 return false;
556 }
557
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000558 /// \brief Pretty print a lock expression for use in error messages.
559 std::string toString(unsigned i = 0) const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000560 assert(isValid());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000561 if (i >= NodeVec.size())
562 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000563
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000564 const SExprNode* N = &NodeVec[i];
565 switch (N->kind()) {
566 case EOP_Nop:
567 return "_";
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000568 case EOP_Wildcard:
569 return "(?)";
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000570 case EOP_This:
571 return "this";
572 case EOP_NVar:
573 case EOP_LVar: {
574 return N->getNamedDecl()->getNameAsString();
575 }
576 case EOP_Dot: {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000577 if (NodeVec[i+1].kind() == EOP_Wildcard) {
578 std::string S = "&";
579 S += N->getNamedDecl()->getQualifiedNameAsString();
580 return S;
581 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000582 std::string FieldName = N->getNamedDecl()->getNameAsString();
583 if (NodeVec[i+1].kind() == EOP_This)
584 return FieldName;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000585
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000586 std::string S = toString(i+1);
587 if (N->isArrow())
588 return S + "->" + FieldName;
589 else
590 return S + "." + FieldName;
591 }
592 case EOP_Call: {
593 std::string S = toString(i+1) + "(";
594 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000595 unsigned ci = getNextSibling(i+1);
596 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000597 S += toString(ci);
598 if (k+1 < NumArgs) S += ",";
599 }
600 S += ")";
601 return S;
602 }
603 case EOP_MCall: {
604 std::string S = "";
605 if (NodeVec[i+1].kind() != EOP_This)
606 S = toString(i+1) + ".";
607 if (const NamedDecl *D = N->getFunctionDecl())
608 S += D->getNameAsString() + "(";
609 else
610 S += "#(";
611 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000612 unsigned ci = getNextSibling(i+1);
613 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000614 S += toString(ci);
615 if (k+1 < NumArgs) S += ",";
616 }
617 S += ")";
618 return S;
619 }
620 case EOP_Index: {
621 std::string S1 = toString(i+1);
622 std::string S2 = toString(i+1 + NodeVec[i+1].size());
623 return S1 + "[" + S2 + "]";
624 }
625 case EOP_Unary: {
626 std::string S = toString(i+1);
627 return "#" + S;
628 }
629 case EOP_Binary: {
630 std::string S1 = toString(i+1);
631 std::string S2 = toString(i+1 + NodeVec[i+1].size());
632 return "(" + S1 + "#" + S2 + ")";
633 }
634 case EOP_Unknown: {
635 unsigned NumChildren = N->arity();
636 if (NumChildren == 0)
637 return "(...)";
638 std::string S = "(";
639 unsigned ci = i+1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000640 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000641 S += toString(ci);
642 if (j+1 < NumChildren) S += "#";
643 }
644 S += ")";
645 return S;
646 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000647 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000648 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000649 }
650};
651
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000652
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000653
654/// \brief A short list of SExprs
655class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000656public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000657 /// \brief Return true if the list contains the specified SExpr
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000658 /// Performs a linear search, because these lists are almost always very small.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000659 bool contains(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000660 for (iterator I=begin(),E=end(); I != E; ++I)
661 if ((*I) == M) return true;
662 return false;
663 }
664
665 /// \brief Push M onto list, bud discard duplicates
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000666 void push_back_nodup(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000667 if (!contains(M)) push_back(M);
668 }
669};
670
671
672
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000673/// \brief This is a helper class that stores info about the most recent
674/// accquire of a Lock.
675///
676/// The main body of the analysis maps MutexIDs to LockDatas.
677struct LockData {
678 SourceLocation AcquireLoc;
679
680 /// \brief LKind stores whether a lock is held shared or exclusively.
681 /// Note that this analysis does not currently support either re-entrant
682 /// locking or lock "upgrading" and "downgrading" between exclusive and
683 /// shared.
684 ///
685 /// FIXME: add support for re-entrant locking and lock up/downgrading
686 LockKind LKind;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000687 bool Managed; // for ScopedLockable objects
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000688 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000689
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000690 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
691 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
692 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000693 {}
694
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000695 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000696 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
697 UnderlyingMutex(Mu)
698 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000699
700 bool operator==(const LockData &other) const {
701 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
702 }
703
704 bool operator!=(const LockData &other) const {
705 return !(*this == other);
706 }
707
708 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000709 ID.AddInteger(AcquireLoc.getRawEncoding());
710 ID.AddInteger(LKind);
711 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000712};
713
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000714
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000715/// \brief A FactEntry stores a single fact that is known at a particular point
716/// in the program execution. Currently, this is information regarding a lock
717/// that is held at that point.
718struct FactEntry {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000719 SExpr MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000720 LockData LDat;
721
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000722 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000723 : MutID(M), LDat(L)
724 { }
725};
726
727
728typedef unsigned short FactID;
729
730/// \brief FactManager manages the memory for all facts that are created during
731/// the analysis of a single routine.
732class FactManager {
733private:
734 std::vector<FactEntry> Facts;
735
736public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000737 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000738 Facts.push_back(FactEntry(M,L));
739 return static_cast<unsigned short>(Facts.size() - 1);
740 }
741
742 const FactEntry& operator[](FactID F) const { return Facts[F]; }
743 FactEntry& operator[](FactID F) { return Facts[F]; }
744};
745
746
747/// \brief A FactSet is the set of facts that are known to be true at a
748/// particular program point. FactSets must be small, because they are
749/// frequently copied, and are thus implemented as a set of indices into a
750/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
751/// locks, so we can get away with doing a linear search for lookup. Note
752/// that a hashtable or map is inappropriate in this case, because lookups
753/// may involve partial pattern matches, rather than exact matches.
754class FactSet {
755private:
756 typedef SmallVector<FactID, 4> FactVec;
757
758 FactVec FactIDs;
759
760public:
761 typedef FactVec::iterator iterator;
762 typedef FactVec::const_iterator const_iterator;
763
764 iterator begin() { return FactIDs.begin(); }
765 const_iterator begin() const { return FactIDs.begin(); }
766
767 iterator end() { return FactIDs.end(); }
768 const_iterator end() const { return FactIDs.end(); }
769
770 bool isEmpty() const { return FactIDs.size() == 0; }
771
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000772 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000773 FactID F = FM.newLock(M, L);
774 FactIDs.push_back(F);
775 return F;
776 }
777
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000778 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000779 unsigned n = FactIDs.size();
780 if (n == 0)
781 return false;
782
783 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000784 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000785 FactIDs[i] = FactIDs[n-1];
786 FactIDs.pop_back();
787 return true;
788 }
789 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000790 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000791 FactIDs.pop_back();
792 return true;
793 }
794 return false;
795 }
796
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000797 LockData* findLock(FactManager& FM, const SExpr& M) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000798 for (const_iterator I=begin(), E=end(); I != E; ++I) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000799 if (FM[*I].MutID.matches(M)) return &FM[*I].LDat;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000800 }
801 return 0;
802 }
803};
804
805
806
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000807/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000808/// been locked.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000809typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000810typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000811
812class LocalVariableMap;
813
Richard Smith2e515622012-02-03 04:45:26 +0000814/// A side (entry or exit) of a CFG node.
815enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000816
817/// CFGBlockInfo is a struct which contains all the information that is
818/// maintained for each block in the CFG. See LocalVariableMap for more
819/// information about the contexts.
820struct CFGBlockInfo {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000821 FactSet EntrySet; // Lockset held at entry to block
822 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000823 LocalVarContext EntryContext; // Context held at entry to block
824 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith2e515622012-02-03 04:45:26 +0000825 SourceLocation EntryLoc; // Location of first statement in block
826 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000827 unsigned EntryIndex; // Used to replay contexts later
828
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000829 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith2e515622012-02-03 04:45:26 +0000830 return Side == CBS_Entry ? EntrySet : ExitSet;
831 }
832 SourceLocation getLocation(CFGBlockSide Side) const {
833 return Side == CBS_Entry ? EntryLoc : ExitLoc;
834 }
835
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000836private:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000837 CFGBlockInfo(LocalVarContext EmptyCtx)
838 : EntryContext(EmptyCtx), ExitContext(EmptyCtx)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000839 { }
840
841public:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000842 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000843};
844
845
846
847// A LocalVariableMap maintains a map from local variables to their currently
848// valid definitions. It provides SSA-like functionality when traversing the
849// CFG. Like SSA, each definition or assignment to a variable is assigned a
850// unique name (an integer), which acts as the SSA name for that definition.
851// The total set of names is shared among all CFG basic blocks.
852// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
853// with their SSA-names. Instead, we compute a Context for each point in the
854// code, which maps local variables to the appropriate SSA-name. This map
855// changes with each assignment.
856//
857// The map is computed in a single pass over the CFG. Subsequent analyses can
858// then query the map to find the appropriate Context for a statement, and use
859// that Context to look up the definitions of variables.
860class LocalVariableMap {
861public:
862 typedef LocalVarContext Context;
863
864 /// A VarDefinition consists of an expression, representing the value of the
865 /// variable, along with the context in which that expression should be
866 /// interpreted. A reference VarDefinition does not itself contain this
867 /// information, but instead contains a pointer to a previous VarDefinition.
868 struct VarDefinition {
869 public:
870 friend class LocalVariableMap;
871
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000872 const NamedDecl *Dec; // The original declaration for this variable.
873 const Expr *Exp; // The expression for this variable, OR
874 unsigned Ref; // Reference to another VarDefinition
875 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000876
877 bool isReference() { return !Exp; }
878
879 private:
880 // Create ordinary variable definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000881 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000882 : Dec(D), Exp(E), Ref(0), Ctx(C)
883 { }
884
885 // Create reference to previous definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000886 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000887 : Dec(D), Exp(0), Ref(R), Ctx(C)
888 { }
889 };
890
891private:
892 Context::Factory ContextFactory;
893 std::vector<VarDefinition> VarDefinitions;
894 std::vector<unsigned> CtxIndices;
895 std::vector<std::pair<Stmt*, Context> > SavedContexts;
896
897public:
898 LocalVariableMap() {
899 // index 0 is a placeholder for undefined variables (aka phi-nodes).
900 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
901 }
902
903 /// Look up a definition, within the given context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000904 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000905 const unsigned *i = Ctx.lookup(D);
906 if (!i)
907 return 0;
908 assert(*i < VarDefinitions.size());
909 return &VarDefinitions[*i];
910 }
911
912 /// Look up the definition for D within the given context. Returns
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000913 /// NULL if the expression is not statically known. If successful, also
914 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000915 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000916 const unsigned *P = Ctx.lookup(D);
917 if (!P)
918 return 0;
919
920 unsigned i = *P;
921 while (i > 0) {
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000922 if (VarDefinitions[i].Exp) {
923 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000924 return VarDefinitions[i].Exp;
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000925 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000926 i = VarDefinitions[i].Ref;
927 }
928 return 0;
929 }
930
931 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
932
933 /// Return the next context after processing S. This function is used by
934 /// clients of the class to get the appropriate context when traversing the
935 /// CFG. It must be called for every assignment or DeclStmt.
936 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
937 if (SavedContexts[CtxIndex+1].first == S) {
938 CtxIndex++;
939 Context Result = SavedContexts[CtxIndex].second;
940 return Result;
941 }
942 return C;
943 }
944
945 void dumpVarDefinitionName(unsigned i) {
946 if (i == 0) {
947 llvm::errs() << "Undefined";
948 return;
949 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000950 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000951 if (!Dec) {
952 llvm::errs() << "<<NULL>>";
953 return;
954 }
955 Dec->printName(llvm::errs());
956 llvm::errs() << "." << i << " " << ((void*) Dec);
957 }
958
959 /// Dumps an ASCII representation of the variable map to llvm::errs()
960 void dump() {
961 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000962 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000963 unsigned Ref = VarDefinitions[i].Ref;
964
965 dumpVarDefinitionName(i);
966 llvm::errs() << " = ";
967 if (Exp) Exp->dump();
968 else {
969 dumpVarDefinitionName(Ref);
970 llvm::errs() << "\n";
971 }
972 }
973 }
974
975 /// Dumps an ASCII representation of a Context to llvm::errs()
976 void dumpContext(Context C) {
977 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000978 const NamedDecl *D = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000979 D->printName(llvm::errs());
980 const unsigned *i = C.lookup(D);
981 llvm::errs() << " -> ";
982 dumpVarDefinitionName(*i);
983 llvm::errs() << "\n";
984 }
985 }
986
987 /// Builds the variable map.
988 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
989 std::vector<CFGBlockInfo> &BlockInfo);
990
991protected:
992 // Get the current context index
993 unsigned getContextIndex() { return SavedContexts.size()-1; }
994
995 // Save the current context for later replay
996 void saveContext(Stmt *S, Context C) {
997 SavedContexts.push_back(std::make_pair(S,C));
998 }
999
1000 // Adds a new definition to the given context, and returns a new context.
1001 // This method should be called when declaring a new variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001002 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001003 assert(!Ctx.contains(D));
1004 unsigned newID = VarDefinitions.size();
1005 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1006 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1007 return NewCtx;
1008 }
1009
1010 // Add a new reference to an existing definition.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001011 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001012 unsigned newID = VarDefinitions.size();
1013 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1014 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1015 return NewCtx;
1016 }
1017
1018 // Updates a definition only if that definition is already in the map.
1019 // This method should be called when assigning to an existing variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001020 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001021 if (Ctx.contains(D)) {
1022 unsigned newID = VarDefinitions.size();
1023 Context NewCtx = ContextFactory.remove(Ctx, D);
1024 NewCtx = ContextFactory.add(NewCtx, D, newID);
1025 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1026 return NewCtx;
1027 }
1028 return Ctx;
1029 }
1030
1031 // Removes a definition from the context, but keeps the variable name
1032 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001033 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001034 Context NewCtx = Ctx;
1035 if (NewCtx.contains(D)) {
1036 NewCtx = ContextFactory.remove(NewCtx, D);
1037 NewCtx = ContextFactory.add(NewCtx, D, 0);
1038 }
1039 return NewCtx;
1040 }
1041
1042 // Remove a definition entirely frmo the context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001043 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001044 Context NewCtx = Ctx;
1045 if (NewCtx.contains(D)) {
1046 NewCtx = ContextFactory.remove(NewCtx, D);
1047 }
1048 return NewCtx;
1049 }
1050
1051 Context intersectContexts(Context C1, Context C2);
1052 Context createReferenceContext(Context C);
1053 void intersectBackEdge(Context C1, Context C2);
1054
1055 friend class VarMapBuilder;
1056};
1057
1058
1059// This has to be defined after LocalVariableMap.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001060CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1061 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001062}
1063
1064
1065/// Visitor which builds a LocalVariableMap
1066class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1067public:
1068 LocalVariableMap* VMap;
1069 LocalVariableMap::Context Ctx;
1070
1071 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1072 : VMap(VM), Ctx(C) {}
1073
1074 void VisitDeclStmt(DeclStmt *S);
1075 void VisitBinaryOperator(BinaryOperator *BO);
1076};
1077
1078
1079// Add new local variables to the variable map
1080void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1081 bool modifiedCtx = false;
1082 DeclGroupRef DGrp = S->getDeclGroup();
1083 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1084 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1085 Expr *E = VD->getInit();
1086
1087 // Add local variables with trivial type to the variable map
1088 QualType T = VD->getType();
1089 if (T.isTrivialType(VD->getASTContext())) {
1090 Ctx = VMap->addDefinition(VD, E, Ctx);
1091 modifiedCtx = true;
1092 }
1093 }
1094 }
1095 if (modifiedCtx)
1096 VMap->saveContext(S, Ctx);
1097}
1098
1099// Update local variable definitions in variable map
1100void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1101 if (!BO->isAssignmentOp())
1102 return;
1103
1104 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1105
1106 // Update the variable map and current context.
1107 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1108 ValueDecl *VDec = DRE->getDecl();
1109 if (Ctx.lookup(VDec)) {
1110 if (BO->getOpcode() == BO_Assign)
1111 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1112 else
1113 // FIXME -- handle compound assignment operators
1114 Ctx = VMap->clearDefinition(VDec, Ctx);
1115 VMap->saveContext(BO, Ctx);
1116 }
1117 }
1118}
1119
1120
1121// Computes the intersection of two contexts. The intersection is the
1122// set of variables which have the same definition in both contexts;
1123// variables with different definitions are discarded.
1124LocalVariableMap::Context
1125LocalVariableMap::intersectContexts(Context C1, Context C2) {
1126 Context Result = C1;
1127 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001128 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001129 unsigned i1 = I.getData();
1130 const unsigned *i2 = C2.lookup(Dec);
1131 if (!i2) // variable doesn't exist on second path
1132 Result = removeDefinition(Dec, Result);
1133 else if (*i2 != i1) // variable exists, but has different definition
1134 Result = clearDefinition(Dec, Result);
1135 }
1136 return Result;
1137}
1138
1139// For every variable in C, create a new variable that refers to the
1140// definition in C. Return a new context that contains these new variables.
1141// (We use this for a naive implementation of SSA on loop back-edges.)
1142LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1143 Context Result = getEmptyContext();
1144 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001145 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001146 unsigned i = I.getData();
1147 Result = addReference(Dec, i, Result);
1148 }
1149 return Result;
1150}
1151
1152// This routine also takes the intersection of C1 and C2, but it does so by
1153// altering the VarDefinitions. C1 must be the result of an earlier call to
1154// createReferenceContext.
1155void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1156 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001157 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001158 unsigned i1 = I.getData();
1159 VarDefinition *VDef = &VarDefinitions[i1];
1160 assert(VDef->isReference());
1161
1162 const unsigned *i2 = C2.lookup(Dec);
1163 if (!i2 || (*i2 != i1))
1164 VDef->Ref = 0; // Mark this variable as undefined
1165 }
1166}
1167
1168
1169// Traverse the CFG in topological order, so all predecessors of a block
1170// (excluding back-edges) are visited before the block itself. At
1171// each point in the code, we calculate a Context, which holds the set of
1172// variable definitions which are visible at that point in execution.
1173// Visible variables are mapped to their definitions using an array that
1174// contains all definitions.
1175//
1176// At join points in the CFG, the set is computed as the intersection of
1177// the incoming sets along each edge, E.g.
1178//
1179// { Context | VarDefinitions }
1180// int x = 0; { x -> x1 | x1 = 0 }
1181// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1182// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1183// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1184// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1185//
1186// This is essentially a simpler and more naive version of the standard SSA
1187// algorithm. Those definitions that remain in the intersection are from blocks
1188// that strictly dominate the current block. We do not bother to insert proper
1189// phi nodes, because they are not used in our analysis; instead, wherever
1190// a phi node would be required, we simply remove that definition from the
1191// context (E.g. x above).
1192//
1193// The initial traversal does not capture back-edges, so those need to be
1194// handled on a separate pass. Whenever the first pass encounters an
1195// incoming back edge, it duplicates the context, creating new definitions
1196// that refer back to the originals. (These correspond to places where SSA
1197// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001198// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001199// node was actually required.) E.g.
1200//
1201// { Context | VarDefinitions }
1202// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1203// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1204// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1205// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1206//
1207void LocalVariableMap::traverseCFG(CFG *CFGraph,
1208 PostOrderCFGView *SortedGraph,
1209 std::vector<CFGBlockInfo> &BlockInfo) {
1210 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1211
1212 CtxIndices.resize(CFGraph->getNumBlockIDs());
1213
1214 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1215 E = SortedGraph->end(); I!= E; ++I) {
1216 const CFGBlock *CurrBlock = *I;
1217 int CurrBlockID = CurrBlock->getBlockID();
1218 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1219
1220 VisitedBlocks.insert(CurrBlock);
1221
1222 // Calculate the entry context for the current block
1223 bool HasBackEdges = false;
1224 bool CtxInit = true;
1225 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1226 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1227 // if *PI -> CurrBlock is a back edge, so skip it
1228 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1229 HasBackEdges = true;
1230 continue;
1231 }
1232
1233 int PrevBlockID = (*PI)->getBlockID();
1234 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1235
1236 if (CtxInit) {
1237 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1238 CtxInit = false;
1239 }
1240 else {
1241 CurrBlockInfo->EntryContext =
1242 intersectContexts(CurrBlockInfo->EntryContext,
1243 PrevBlockInfo->ExitContext);
1244 }
1245 }
1246
1247 // Duplicate the context if we have back-edges, so we can call
1248 // intersectBackEdges later.
1249 if (HasBackEdges)
1250 CurrBlockInfo->EntryContext =
1251 createReferenceContext(CurrBlockInfo->EntryContext);
1252
1253 // Create a starting context index for the current block
1254 saveContext(0, CurrBlockInfo->EntryContext);
1255 CurrBlockInfo->EntryIndex = getContextIndex();
1256
1257 // Visit all the statements in the basic block.
1258 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1259 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1260 BE = CurrBlock->end(); BI != BE; ++BI) {
1261 switch (BI->getKind()) {
1262 case CFGElement::Statement: {
1263 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1264 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1265 break;
1266 }
1267 default:
1268 break;
1269 }
1270 }
1271 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1272
1273 // Mark variables on back edges as "unknown" if they've been changed.
1274 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1275 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1276 // if CurrBlock -> *SI is *not* a back edge
1277 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1278 continue;
1279
1280 CFGBlock *FirstLoopBlock = *SI;
1281 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1282 Context LoopEnd = CurrBlockInfo->ExitContext;
1283 intersectBackEdge(LoopBegin, LoopEnd);
1284 }
1285 }
1286
1287 // Put an extra entry at the end of the indexed context array
1288 unsigned exitID = CFGraph->getExit().getBlockID();
1289 saveContext(0, BlockInfo[exitID].ExitContext);
1290}
1291
Richard Smith2e515622012-02-03 04:45:26 +00001292/// Find the appropriate source locations to use when producing diagnostics for
1293/// each block in the CFG.
1294static void findBlockLocations(CFG *CFGraph,
1295 PostOrderCFGView *SortedGraph,
1296 std::vector<CFGBlockInfo> &BlockInfo) {
1297 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1298 E = SortedGraph->end(); I!= E; ++I) {
1299 const CFGBlock *CurrBlock = *I;
1300 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1301
1302 // Find the source location of the last statement in the block, if the
1303 // block is not empty.
1304 if (const Stmt *S = CurrBlock->getTerminator()) {
1305 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1306 } else {
1307 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1308 BE = CurrBlock->rend(); BI != BE; ++BI) {
1309 // FIXME: Handle other CFGElement kinds.
1310 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1311 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1312 break;
1313 }
1314 }
1315 }
1316
1317 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1318 // This block contains at least one statement. Find the source location
1319 // of the first statement in the block.
1320 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1321 BE = CurrBlock->end(); BI != BE; ++BI) {
1322 // FIXME: Handle other CFGElement kinds.
1323 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1324 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1325 break;
1326 }
1327 }
1328 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1329 CurrBlock != &CFGraph->getExit()) {
1330 // The block is empty, and has a single predecessor. Use its exit
1331 // location.
1332 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1333 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1334 }
1335 }
1336}
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001337
1338/// \brief Class which implements the core thread safety analysis routines.
1339class ThreadSafetyAnalyzer {
1340 friend class BuildLockset;
1341
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001342 ThreadSafetyHandler &Handler;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001343 LocalVariableMap LocalVarMap;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001344 FactManager FactMan;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001345 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001346
1347public:
1348 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1349
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001350 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1351 void removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001352 SourceLocation UnlockLoc, bool FullyRemove=false);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001353
1354 template <typename AttrType>
1355 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1356 const NamedDecl *D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001357
1358 template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001359 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1360 const NamedDecl *D,
1361 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1362 Expr *BrE, bool Neg);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001363
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001364 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1365 bool &Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001366
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001367 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1368 const CFGBlock* PredBlock,
1369 const CFGBlock *CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001370
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001371 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1372 SourceLocation JoinLoc,
1373 LockErrorKind LEK1, LockErrorKind LEK2,
1374 bool Modify=true);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001375
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001376 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1377 SourceLocation JoinLoc, LockErrorKind LEK1,
1378 bool Modify=true) {
1379 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001380 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001381
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001382 void runAnalysis(AnalysisDeclContext &AC);
1383};
1384
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001385
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001386/// \brief Add a new lock to the lockset, warning if the lock is already there.
1387/// \param Mutex -- the Mutex expression for the lock
1388/// \param LDat -- the LockData for the lock
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001389void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001390 const LockData &LDat) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001391 // FIXME: deal with acquired before/after annotations.
1392 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001393 if (Mutex.shouldIgnore())
1394 return;
1395
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001396 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001397 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001398 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001399 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001400 }
1401}
1402
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001403
1404/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenekad0fe032012-08-22 23:50:41 +00001405/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001406/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001407void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001408 const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001409 SourceLocation UnlockLoc,
1410 bool FullyRemove) {
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001411 if (Mutex.shouldIgnore())
1412 return;
1413
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001414 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001415 if (!LDat) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001416 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001417 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001418 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001419
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001420 if (LDat->UnderlyingMutex.isValid()) {
1421 // This is scoped lockable object, which manages the real mutex.
1422 if (FullyRemove) {
1423 // We're destroying the managing object.
1424 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001425 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1426 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001427 } else {
1428 // We're releasing the underlying mutex, but not destroying the
1429 // managing object. Warn on dual release.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001430 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001431 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001432 UnlockLoc);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001433 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001434 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1435 return;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001436 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001437 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001438 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001439}
1440
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001441
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001442/// \brief Extract the list of mutexIDs from the attribute on an expression,
1443/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001444template <typename AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001445void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1446 Expr *Exp, const NamedDecl *D) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001447 typedef typename AttrType::args_iterator iterator_type;
1448
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001449 if (Attr->args_size() == 0) {
1450 // The mutex held is the "this" object.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001451 SExpr Mu(0, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001452 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001453 SExpr::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001454 else
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001455 Mtxs.push_back_nodup(Mu);
1456 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001457 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001458
1459 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001460 SExpr Mu(*I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001461 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001462 SExpr::warnInvalidLock(Handler, *I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001463 else
1464 Mtxs.push_back_nodup(Mu);
1465 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001466}
1467
1468
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001469/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1470/// trylock applies to the given edge, then push them onto Mtxs, discarding
1471/// any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001472template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001473void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1474 Expr *Exp, const NamedDecl *D,
1475 const CFGBlock *PredBlock,
1476 const CFGBlock *CurrBlock,
1477 Expr *BrE, bool Neg) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001478 // Find out which branch has the lock
1479 bool branch = 0;
1480 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1481 branch = BLE->getValue();
1482 }
1483 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1484 branch = ILE->getValue().getBoolValue();
1485 }
1486 int branchnum = branch ? 0 : 1;
1487 if (Neg) branchnum = !branchnum;
1488
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001489 // If we've taken the trylock branch, then add the lock
1490 int i = 0;
1491 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1492 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1493 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001494 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001495 }
1496 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001497}
1498
1499
DeLesley Hutchins13106112012-07-10 21:47:55 +00001500bool getStaticBooleanValue(Expr* E, bool& TCond) {
1501 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1502 TCond = false;
1503 return true;
1504 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1505 TCond = BLE->getValue();
1506 return true;
1507 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1508 TCond = ILE->getValue().getBoolValue();
1509 return true;
1510 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1511 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1512 }
1513 return false;
1514}
1515
1516
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001517// If Cond can be traced back to a function call, return the call expression.
1518// The negate variable should be called with false, and will be set to true
1519// if the function call is negated, e.g. if (!mu.tryLock(...))
1520const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1521 LocalVarContext C,
1522 bool &Negate) {
1523 if (!Cond)
1524 return 0;
1525
1526 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1527 return CallExp;
1528 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001529 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1530 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1531 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001532 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1533 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1534 }
1535 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1536 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1537 return getTrylockCallExpr(E, C, Negate);
1538 }
1539 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1540 if (UOP->getOpcode() == UO_LNot) {
1541 Negate = !Negate;
1542 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1543 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001544 return 0;
1545 }
1546 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1547 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1548 if (BOP->getOpcode() == BO_NE)
1549 Negate = !Negate;
1550
1551 bool TCond = false;
1552 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1553 if (!TCond) Negate = !Negate;
1554 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1555 }
1556 else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1557 if (!TCond) Negate = !Negate;
1558 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1559 }
1560 return 0;
1561 }
1562 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001563 }
1564 // FIXME -- handle && and || as well.
DeLesley Hutchins13106112012-07-10 21:47:55 +00001565 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001566}
1567
1568
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001569/// \brief Find the lockset that holds on the edge between PredBlock
1570/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1571/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001572void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1573 const FactSet &ExitSet,
1574 const CFGBlock *PredBlock,
1575 const CFGBlock *CurrBlock) {
1576 Result = ExitSet;
1577
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001578 if (!PredBlock->getTerminatorCondition())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001579 return;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001580
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001581 bool Negate = false;
1582 const Stmt *Cond = PredBlock->getTerminatorCondition();
1583 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1584 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1585
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001586 CallExpr *Exp =
1587 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001588 if (!Exp)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001589 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001590
1591 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1592 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001593 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001594
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001595
1596 MutexIDList ExclusiveLocksToAdd;
1597 MutexIDList SharedLocksToAdd;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001598
1599 // If the condition is a call to a Trylock function, then grab the attributes
1600 AttrVec &ArgAttrs = FunDecl->getAttrs();
1601 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1602 Attr *Attr = ArgAttrs[i];
1603 switch (Attr->getKind()) {
1604 case attr::ExclusiveTrylockFunction: {
1605 ExclusiveTrylockFunctionAttr *A =
1606 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001607 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1608 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001609 break;
1610 }
1611 case attr::SharedTrylockFunction: {
1612 SharedTrylockFunctionAttr *A =
1613 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001614 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1615 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001616 break;
1617 }
1618 default:
1619 break;
1620 }
1621 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001622
1623 // Add and remove locks.
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001624 SourceLocation Loc = Exp->getExprLoc();
1625 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001626 addLock(Result, ExclusiveLocksToAdd[i],
1627 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001628 }
1629 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001630 addLock(Result, SharedLocksToAdd[i],
1631 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001632 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001633}
1634
1635
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001636/// \brief We use this class to visit different types of expressions in
1637/// CFGBlocks, and build up the lockset.
1638/// An expression may cause us to add or remove locks from the lockset, or else
1639/// output error messages related to missing locks.
1640/// FIXME: In future, we may be able to not inherit from a visitor.
1641class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001642 friend class ThreadSafetyAnalyzer;
1643
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001644 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001645 FactSet FSet;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001646 LocalVariableMap::Context LVarCtx;
1647 unsigned CtxIndex;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001648
1649 // Helper functions
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001650 const ValueDecl *getValueDecl(Expr *Exp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001651
1652 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1653 Expr *MutexExp, ProtectedOperationKind POK);
1654
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001655 void checkAccess(Expr *Exp, AccessKind AK);
1656 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001657 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001658
1659 /// \brief Returns true if the lockset contains a lock, regardless of whether
1660 /// the lock is held exclusively or shared.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001661 bool locksetContains(const SExpr &Mu) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001662 return FSet.findLock(Analyzer->FactMan, Mu);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001663 }
1664
1665 /// \brief Returns true if the lockset contains a lock with the passed in
1666 /// locktype.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001667 bool locksetContains(const SExpr &Mu, LockKind KindRequested) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001668 const LockData *LockHeld = FSet.findLock(Analyzer->FactMan, Mu);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001669 return (LockHeld && KindRequested == LockHeld->LKind);
1670 }
1671
1672 /// \brief Returns true if the lockset contains a lock with at least the
1673 /// passed in locktype. So for example, if we pass in LK_Shared, this function
1674 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
1675 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001676 bool locksetContainsAtLeast(const SExpr &Lock,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001677 LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001678 switch (KindRequested) {
1679 case LK_Shared:
1680 return locksetContains(Lock);
1681 case LK_Exclusive:
1682 return locksetContains(Lock, KindRequested);
1683 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00001684 llvm_unreachable("Unknown LockKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001685 }
1686
1687public:
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001688 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001689 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001690 Analyzer(Anlzr),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001691 FSet(Info.EntrySet),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001692 LVarCtx(Info.EntryContext),
1693 CtxIndex(Info.EntryIndex)
1694 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001695
1696 void VisitUnaryOperator(UnaryOperator *UO);
1697 void VisitBinaryOperator(BinaryOperator *BO);
1698 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001699 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001700 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001701 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001702};
1703
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001704
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001705/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1706const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1707 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1708 return DR->getDecl();
1709
1710 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1711 return ME->getMemberDecl();
1712
1713 return 0;
1714}
1715
1716/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001717/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001718void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1719 AccessKind AK, Expr *MutexExp,
1720 ProtectedOperationKind POK) {
1721 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001722
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001723 SExpr Mutex(MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001724 if (!Mutex.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001725 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001726 else if (Mutex.shouldIgnore())
1727 return; // A Nop is an invalid mutex that we've decided to ignore.
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001728 else if (!locksetContainsAtLeast(Mutex, LK))
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001729 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001730 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001731}
1732
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001733/// \brief This method identifies variable dereferences and checks pt_guarded_by
1734/// and pt_guarded_var annotations. Note that we only check these annotations
1735/// at the time a pointer is dereferenced.
1736/// FIXME: We need to check for other types of pointer dereferences
1737/// (e.g. [], ->) and deal with them here.
1738/// \param Exp An expression that has been read or written.
1739void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1740 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1741 if (!UO || UO->getOpcode() != clang::UO_Deref)
1742 return;
1743 Exp = UO->getSubExpr()->IgnoreParenCasts();
1744
1745 const ValueDecl *D = getValueDecl(Exp);
1746 if(!D || !D->hasAttrs())
1747 return;
1748
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001749 if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001750 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1751 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001752
1753 const AttrVec &ArgAttrs = D->getAttrs();
1754 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1755 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1756 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1757}
1758
1759/// \brief Checks guarded_by and guarded_var attributes.
1760/// Whenever we identify an access (read or write) of a DeclRefExpr or
1761/// MemberExpr, we need to check whether there are any guarded_by or
1762/// guarded_var attributes, and make sure we hold the appropriate mutexes.
1763void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1764 const ValueDecl *D = getValueDecl(Exp);
1765 if(!D || !D->hasAttrs())
1766 return;
1767
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001768 if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001769 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1770 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001771
1772 const AttrVec &ArgAttrs = D->getAttrs();
1773 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1774 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1775 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1776}
1777
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001778/// \brief Process a function call, method call, constructor call,
1779/// or destructor call. This involves looking at the attributes on the
1780/// corresponding function/method/constructor/destructor, issuing warnings,
1781/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001782///
1783/// FIXME: For classes annotated with one of the guarded annotations, we need
1784/// to treat const method calls as reads and non-const method calls as writes,
1785/// and check that the appropriate locks are held. Non-const method calls with
1786/// the same signature as const method calls can be also treated as reads.
1787///
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001788void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1789 const AttrVec &ArgAttrs = D->getAttrs();
1790 MutexIDList ExclusiveLocksToAdd;
1791 MutexIDList SharedLocksToAdd;
1792 MutexIDList LocksToRemove;
1793
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001794 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001795 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1796 switch (At->getKind()) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001797 // When we encounter an exclusive lock function, we need to add the lock
1798 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001799 case attr::ExclusiveLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001800 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1801 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001802 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001803 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001804
1805 // When we encounter a shared lock function, we need to add the lock
1806 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001807 case attr::SharedLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001808 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1809 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001810 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001811 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001812
1813 // When we encounter an unlock function, we need to remove unlocked
1814 // mutexes from the lockset, and flag a warning if they are not there.
1815 case attr::UnlockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001816 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1817 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001818 break;
1819 }
1820
1821 case attr::ExclusiveLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001822 ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001823
1824 for (ExclusiveLocksRequiredAttr::args_iterator
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001825 I = A->args_begin(), E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001826 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1827 break;
1828 }
1829
1830 case attr::SharedLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001831 SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001832
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001833 for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1834 E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001835 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1836 break;
1837 }
1838
1839 case attr::LocksExcluded: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001840 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
1841 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1842 E = A->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001843 SExpr Mutex(*I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001844 if (!Mutex.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001845 SExpr::warnInvalidLock(Analyzer->Handler, *I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001846 else if (locksetContains(Mutex))
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001847 Analyzer->Handler.handleFunExcludesLock(D->getName(),
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001848 Mutex.toString(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001849 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001850 }
1851 break;
1852 }
1853
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001854 // Ignore other (non thread-safety) attributes
1855 default:
1856 break;
1857 }
1858 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001859
1860 // Figure out if we're calling the constructor of scoped lockable class
1861 bool isScopedVar = false;
1862 if (VD) {
1863 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1864 const CXXRecordDecl* PD = CD->getParent();
1865 if (PD && PD->getAttr<ScopedLockableAttr>())
1866 isScopedVar = true;
1867 }
1868 }
1869
1870 // Add locks.
1871 SourceLocation Loc = Exp->getExprLoc();
1872 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001873 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
1874 LockData(Loc, LK_Exclusive, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001875 }
1876 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001877 Analyzer->addLock(FSet, SharedLocksToAdd[i],
1878 LockData(Loc, LK_Shared, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001879 }
1880
1881 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1882 // FIXME -- this doesn't work if we acquire multiple locks.
1883 if (isScopedVar) {
1884 SourceLocation MLoc = VD->getLocation();
1885 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001886 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001887
1888 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001889 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
1890 ExclusiveLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001891 }
1892 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001893 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
1894 SharedLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001895 }
1896 }
1897
1898 // Remove locks.
1899 // FIXME -- should only fully remove if the attribute refers to 'this'.
1900 bool Dtor = isa<CXXDestructorDecl>(D);
1901 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001902 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001903 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001904}
1905
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +00001906
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001907/// \brief For unary operations which read and write a variable, we need to
1908/// check whether we hold any required mutexes. Reads are checked in
1909/// VisitCastExpr.
1910void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1911 switch (UO->getOpcode()) {
1912 case clang::UO_PostDec:
1913 case clang::UO_PostInc:
1914 case clang::UO_PreDec:
1915 case clang::UO_PreInc: {
1916 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1917 checkAccess(SubExp, AK_Written);
1918 checkDereference(SubExp, AK_Written);
1919 break;
1920 }
1921 default:
1922 break;
1923 }
1924}
1925
1926/// For binary operations which assign to a variable (writes), we need to check
1927/// whether we hold any required mutexes.
1928/// FIXME: Deal with non-primitive types.
1929void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1930 if (!BO->isAssignmentOp())
1931 return;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001932
1933 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001934 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001935
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001936 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1937 checkAccess(LHSExp, AK_Written);
1938 checkDereference(LHSExp, AK_Written);
1939}
1940
1941/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1942/// need to ensure we hold any required mutexes.
1943/// FIXME: Deal with non-primitive types.
1944void BuildLockset::VisitCastExpr(CastExpr *CE) {
1945 if (CE->getCastKind() != CK_LValueToRValue)
1946 return;
1947 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
1948 checkAccess(SubExp, AK_Read);
1949 checkDereference(SubExp, AK_Read);
1950}
1951
1952
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001953void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001954 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1955 if(!D || !D->hasAttrs())
1956 return;
1957 handleCall(Exp, D);
1958}
1959
1960void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001961 // FIXME -- only handles constructors in DeclStmt below.
1962}
1963
1964void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001965 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001966 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001967
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001968 DeclGroupRef DGrp = S->getDeclGroup();
1969 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1970 Decl *D = *I;
1971 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1972 Expr *E = VD->getInit();
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +00001973 // handle constructors that involve temporaries
1974 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1975 E = EWC->getSubExpr();
1976
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001977 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1978 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1979 if (!CtorD || !CtorD->hasAttrs())
1980 return;
1981 handleCall(CE, CtorD, VD);
1982 }
1983 }
1984 }
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001985}
1986
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001987
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001988
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001989/// \brief Compute the intersection of two locksets and issue warnings for any
1990/// locks in the symmetric difference.
1991///
1992/// This function is used at a merge point in the CFG when comparing the lockset
1993/// of each branch being merged. For example, given the following sequence:
1994/// A; if () then B; else C; D; we need to check that the lockset after B and C
1995/// are the same. In the event of a difference, we use the intersection of these
1996/// two locksets at the start of D.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001997///
Ted Kremenekad0fe032012-08-22 23:50:41 +00001998/// \param FSet1 The first lockset.
1999/// \param FSet2 The second lockset.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002000/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002001/// \param LEK1 The error message to report if a mutex is missing from LSet1
2002/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002003void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2004 const FactSet &FSet2,
2005 SourceLocation JoinLoc,
2006 LockErrorKind LEK1,
2007 LockErrorKind LEK2,
2008 bool Modify) {
2009 FactSet FSet1Orig = FSet1;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002010
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002011 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2012 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002013 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002014 const LockData &LDat2 = FactMan[*I].LDat;
2015
2016 if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002017 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002018 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002019 LDat2.AcquireLoc,
2020 LDat1->AcquireLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002021 if (Modify && LDat1->LKind != LK_Exclusive) {
2022 FSet1.removeLock(FactMan, FSet2Mutex);
2023 FSet1.addLock(FactMan, FSet2Mutex, LDat2);
2024 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002025 }
2026 } else {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002027 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002028 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002029 // If this is a scoped lock that manages another mutex, and if the
2030 // underlying mutex is still held, then warn about the underlying
2031 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002032 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002033 LDat2.AcquireLoc,
2034 JoinLoc, LEK1);
2035 }
2036 }
2037 else if (!LDat2.Managed)
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002038 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002039 LDat2.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002040 JoinLoc, LEK1);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002041 }
2042 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002043
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002044 for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
2045 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002046 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002047 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00002048
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002049 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002050 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002051 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002052 // If this is a scoped lock that manages another mutex, and if the
2053 // underlying mutex is still held, then warn about the underlying
2054 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002055 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002056 LDat1.AcquireLoc,
2057 JoinLoc, LEK1);
2058 }
2059 }
2060 else if (!LDat1.Managed)
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002061 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002062 LDat1.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002063 JoinLoc, LEK2);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002064 if (Modify)
2065 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002066 }
2067 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002068}
2069
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002070
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002071
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002072/// \brief Check a function's CFG for thread-safety violations.
2073///
2074/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2075/// at the end of each block, and issue warnings for thread safety violations.
2076/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002077void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002078 CFG *CFGraph = AC.getCFG();
2079 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002080 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2081
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002082 // AC.dumpCFG(true);
2083
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002084 if (!D)
2085 return; // Ignore anonymous functions for now.
2086 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
2087 return;
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002088 // FIXME: Do something a bit more intelligent inside constructor and
2089 // destructor code. Constructors and destructors must assume unique access
2090 // to 'this', so checks on member variable access is disabled, but we should
2091 // still enable checks on other objects.
2092 if (isa<CXXConstructorDecl>(D))
2093 return; // Don't check inside constructors.
2094 if (isa<CXXDestructorDecl>(D))
2095 return; // Don't check inside destructors.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002096
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002097 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002098 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002099
2100 // We need to explore the CFG via a "topological" ordering.
2101 // That way, we will be guaranteed to have information about required
2102 // predecessor locksets when exploring a new block.
Ted Kremenek439ed162011-10-22 02:14:27 +00002103 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2104 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002105
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002106 // Compute SSA names for local variables
2107 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2108
Richard Smith2e515622012-02-03 04:45:26 +00002109 // Fill in source locations for all CFGBlocks.
2110 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2111
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002112 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002113 // to initial lockset. Also turn off checking for lock and unlock functions.
2114 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek439ed162011-10-22 02:14:27 +00002115 if (!SortedGraph->empty() && D->hasAttrs()) {
2116 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002117 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002118 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002119
2120 MutexIDList ExclusiveLocksToAdd;
2121 MutexIDList SharedLocksToAdd;
2122
2123 SourceLocation Loc = D->getLocation();
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002124 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002125 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002126 Loc = Attr->getLocation();
2127 if (ExclusiveLocksRequiredAttr *A
2128 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
2129 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2130 } else if (SharedLocksRequiredAttr *A
2131 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
2132 getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002133 } else if (isa<UnlockFunctionAttr>(Attr)) {
2134 // Don't try to check unlock functions for now
2135 return;
2136 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
2137 // Don't try to check lock functions for now
2138 return;
2139 } else if (isa<SharedLockFunctionAttr>(Attr)) {
2140 // Don't try to check lock functions for now
2141 return;
DeLesley Hutchins76f0a6e2012-07-02 21:59:24 +00002142 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2143 // Don't try to check trylock functions for now
2144 return;
2145 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2146 // Don't try to check trylock functions for now
2147 return;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002148 }
2149 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002150
2151 // FIXME -- Loc can be wrong here.
2152 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002153 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2154 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002155 }
2156 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002157 addLock(InitialLockset, SharedLocksToAdd[i],
2158 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002159 }
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002160 }
2161
Ted Kremenek439ed162011-10-22 02:14:27 +00002162 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2163 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002164 const CFGBlock *CurrBlock = *I;
2165 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002166 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002167
2168 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002169 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002170
2171 // Iterate through the predecessor blocks and warn if the lockset for all
2172 // predecessors is not the same. We take the entry lockset of the current
2173 // block to be the intersection of all previous locksets.
2174 // FIXME: By keeping the intersection, we may output more errors in future
2175 // for a lock which is not in the intersection, but was in the union. We
2176 // may want to also keep the union in future. As an example, let's say
2177 // the intersection contains Mutex L, and the union contains L and M.
2178 // Later we unlock M. At this point, we would output an error because we
2179 // never locked M; although the real error is probably that we forgot to
2180 // lock M on all code paths. Conversely, let's say that later we lock M.
2181 // In this case, we should compare against the intersection instead of the
2182 // union because the real error is probably that we forgot to unlock M on
2183 // all code paths.
2184 bool LocksetInitialized = false;
Richard Smithaacde712012-02-03 03:30:07 +00002185 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002186 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2187 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2188
2189 // if *PI -> CurrBlock is a back edge
2190 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2191 continue;
2192
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00002193 // Ignore edges from blocks that can't return.
2194 if ((*PI)->hasNoReturnElement())
2195 continue;
2196
Richard Smithaacde712012-02-03 03:30:07 +00002197 // If the previous block ended in a 'continue' or 'break' statement, then
2198 // a difference in locksets is probably due to a bug in that block, rather
2199 // than in some other predecessor. In that case, keep the other
2200 // predecessor's lockset.
2201 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2202 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2203 SpecialBlocks.push_back(*PI);
2204 continue;
2205 }
2206 }
2207
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002208 int PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002209 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002210 FactSet PrevLockset;
2211 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002212
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002213 if (!LocksetInitialized) {
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002214 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002215 LocksetInitialized = true;
2216 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002217 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2218 CurrBlockInfo->EntryLoc,
2219 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002220 }
2221 }
2222
Richard Smithaacde712012-02-03 03:30:07 +00002223 // Process continue and break blocks. Assume that the lockset for the
2224 // resulting block is unaffected by any discrepancies in them.
2225 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2226 SpecialI < SpecialN; ++SpecialI) {
2227 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2228 int PrevBlockID = PrevBlock->getBlockID();
2229 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2230
2231 if (!LocksetInitialized) {
2232 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2233 LocksetInitialized = true;
2234 } else {
2235 // Determine whether this edge is a loop terminator for diagnostic
2236 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2237 // it might also be part of a switch. Also, a subsequent destructor
2238 // might add to the lockset, in which case the real issue might be a
2239 // double lock on the other path.
2240 const Stmt *Terminator = PrevBlock->getTerminator();
2241 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2242
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002243 FactSet PrevLockset;
2244 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2245 PrevBlock, CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002246
Richard Smithaacde712012-02-03 03:30:07 +00002247 // Do not update EntrySet.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002248 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2249 PrevBlockInfo->ExitLoc,
Richard Smithaacde712012-02-03 03:30:07 +00002250 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002251 : LEK_LockedSomePredecessors,
2252 false);
Richard Smithaacde712012-02-03 03:30:07 +00002253 }
2254 }
2255
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002256 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2257
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002258 // Visit all the statements in the basic block.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002259 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2260 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002261 switch (BI->getKind()) {
2262 case CFGElement::Statement: {
2263 const CFGStmt *CS = cast<CFGStmt>(&*BI);
2264 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
2265 break;
2266 }
2267 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2268 case CFGElement::AutomaticObjectDtor: {
2269 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
2270 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
2271 AD->getDestructorDecl(AC.getASTContext()));
2272 if (!DD->hasAttrs())
2273 break;
2274
2275 // Create a dummy expression,
2276 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
John McCallf4b88a42012-03-10 09:33:50 +00002277 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002278 AD->getTriggerStmt()->getLocEnd());
2279 LocksetBuilder.handleCall(&DRE, DD);
2280 break;
2281 }
2282 default:
2283 break;
2284 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002285 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002286 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002287
2288 // For every back edge from CurrBlock (the end of the loop) to another block
2289 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2290 // the one held at the beginning of FirstLoopBlock. We can look up the
2291 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2292 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2293 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2294
2295 // if CurrBlock -> *SI is *not* a back edge
2296 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2297 continue;
2298
2299 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002300 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2301 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2302 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2303 PreLoop->EntryLoc,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002304 LEK_LockedSomeLoopIterations,
2305 false);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002306 }
2307 }
2308
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002309 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2310 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00002311
2312 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002313 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
2314 Final->ExitLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002315 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002316 LEK_NotLockedAtEndOfFunction,
2317 false);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002318}
2319
2320} // end anonymous namespace
2321
2322
2323namespace clang {
2324namespace thread_safety {
2325
2326/// \brief Check a function's CFG for thread-safety violations.
2327///
2328/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2329/// at the end of each block, and issue warnings for thread safety violations.
2330/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002331void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002332 ThreadSafetyHandler &Handler) {
2333 ThreadSafetyAnalyzer Analyzer(Handler);
2334 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002335}
2336
2337/// \brief Helper function that returns a LockKind required for the given level
2338/// of access.
2339LockKind getLockKindFromAccessKind(AccessKind AK) {
2340 switch (AK) {
2341 case AK_Read :
2342 return LK_Shared;
2343 case AK_Written :
2344 return LK_Exclusive;
2345 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00002346 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002347}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002348
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002349}} // end namespace clang::thread_safety