blob: bc8a3c0d1a200564730a746cec2eb80f54b3fbfe [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 {
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +000073 EOP_Nop, ///< No-op
74 EOP_Wildcard, ///< Matches anything.
75 EOP_Universal, ///< Universal lock.
76 EOP_This, ///< This keyword.
77 EOP_NVar, ///< Named variable.
78 EOP_LVar, ///< Local variable.
79 EOP_Dot, ///< Field access
80 EOP_Call, ///< Function call
81 EOP_MCall, ///< Method call
82 EOP_Index, ///< Array index
83 EOP_Unary, ///< Unary operation
84 EOP_Binary, ///< Binary operation
85 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000086 };
87
88
89 class SExprNode {
90 private:
Ted Kremenekad0fe032012-08-22 23:50:41 +000091 unsigned char Op; ///< Opcode of the root node
92 unsigned char Flags; ///< Additional opcode-specific data
93 unsigned short Sz; ///< Number of child nodes
94 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000095
96 public:
97 SExprNode(ExprOp O, unsigned F, const void* D)
98 : Op(static_cast<unsigned char>(O)),
99 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
100 { }
101
102 unsigned size() const { return Sz; }
103 void setSize(unsigned S) { Sz = S; }
104
105 ExprOp kind() const { return static_cast<ExprOp>(Op); }
106
107 const NamedDecl* getNamedDecl() const {
108 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
109 return reinterpret_cast<const NamedDecl*>(Data);
110 }
111
112 const NamedDecl* getFunctionDecl() const {
113 assert(Op == EOP_Call || Op == EOP_MCall);
114 return reinterpret_cast<const NamedDecl*>(Data);
115 }
116
117 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
118 void setArrow(bool A) { Flags = A ? 1 : 0; }
119
120 unsigned arity() const {
121 switch (Op) {
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000122 case EOP_Nop: return 0;
123 case EOP_Wildcard: return 0;
124 case EOP_Universal: return 0;
125 case EOP_NVar: return 0;
126 case EOP_LVar: return 0;
127 case EOP_This: return 0;
128 case EOP_Dot: return 1;
129 case EOP_Call: return Flags+1; // First arg is function.
130 case EOP_MCall: return Flags+1; // First arg is implicit obj.
131 case EOP_Index: return 2;
132 case EOP_Unary: return 1;
133 case EOP_Binary: return 2;
134 case EOP_Unknown: return Flags;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000135 }
136 return 0;
137 }
138
139 bool operator==(const SExprNode& Other) const {
140 // Ignore flags and size -- they don't matter.
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000141 return (Op == Other.Op &&
142 Data == Other.Data);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000143 }
144
145 bool operator!=(const SExprNode& Other) const {
146 return !(*this == Other);
147 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000148
149 bool matches(const SExprNode& Other) const {
150 return (*this == Other) ||
151 (Op == EOP_Wildcard) ||
152 (Other.Op == EOP_Wildcard);
153 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000154 };
155
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000156
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000157 /// \brief Encapsulates the lexical context of a function call. The lexical
158 /// context includes the arguments to the call, including the implicit object
159 /// argument. When an attribute containing a mutex expression is attached to
160 /// a method, the expression may refer to formal parameters of the method.
161 /// Actual arguments must be substituted for formal parameters to derive
162 /// the appropriate mutex expression in the lexical context where the function
163 /// is called. PrevCtx holds the context in which the arguments themselves
164 /// should be evaluated; multiple calling contexts can be chained together
165 /// by the lock_returned attribute.
166 struct CallingContext {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000167 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
168 Expr* SelfArg; // Implicit object argument -- e.g. 'this'
169 bool SelfArrow; // is Self referred to with -> or .?
170 unsigned NumArgs; // Number of funArgs
171 Expr** FunArgs; // Function arguments
172 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000173
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000174 CallingContext(const NamedDecl *D = 0, Expr *S = 0,
175 unsigned N = 0, Expr **A = 0, CallingContext *P = 0)
176 : AttrDecl(D), SelfArg(S), SelfArrow(false),
177 NumArgs(N), FunArgs(A), PrevCtx(P)
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000178 { }
179 };
180
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000181 typedef SmallVector<SExprNode, 4> NodeVector;
182
183private:
184 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
185 // the list to be traversed as a tree.
186 NodeVector NodeVec;
187
188private:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000189 unsigned makeNop() {
190 NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
191 return NodeVec.size()-1;
192 }
193
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000194 unsigned makeWildcard() {
195 NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
196 return NodeVec.size()-1;
197 }
198
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000199 unsigned makeUniversal() {
200 NodeVec.push_back(SExprNode(EOP_Universal, 0, 0));
201 return NodeVec.size()-1;
202 }
203
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000204 unsigned makeNamedVar(const NamedDecl *D) {
205 NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
206 return NodeVec.size()-1;
207 }
208
209 unsigned makeLocalVar(const NamedDecl *D) {
210 NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
211 return NodeVec.size()-1;
212 }
213
214 unsigned makeThis() {
215 NodeVec.push_back(SExprNode(EOP_This, 0, 0));
216 return NodeVec.size()-1;
217 }
218
219 unsigned makeDot(const NamedDecl *D, bool Arrow) {
220 NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
221 return NodeVec.size()-1;
222 }
223
224 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
225 NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
226 return NodeVec.size()-1;
227 }
228
DeLesley Hutchins186af2d2012-09-20 22:18:02 +0000229 // Grab the very first declaration of virtual method D
230 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
231 while (true) {
232 D = D->getCanonicalDecl();
233 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
234 E = D->end_overridden_methods();
235 if (I == E)
236 return D; // Method does not override anything
237 D = *I; // FIXME: this does not work with multiple inheritance.
238 }
239 return 0;
240 }
241
242 unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
243 NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, getFirstVirtualDecl(D)));
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000244 return NodeVec.size()-1;
245 }
246
247 unsigned makeIndex() {
248 NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
249 return NodeVec.size()-1;
250 }
251
252 unsigned makeUnary() {
253 NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
254 return NodeVec.size()-1;
255 }
256
257 unsigned makeBinary() {
258 NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
259 return NodeVec.size()-1;
260 }
261
262 unsigned makeUnknown(unsigned Arity) {
263 NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
264 return NodeVec.size()-1;
265 }
266
267 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000268 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000269 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000270 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000271 ///
272 /// NDeref returns the number of Derefence and AddressOf operations
273 /// preceeding the Expr; this is used to decide whether to pretty-print
274 /// SExprs with . or ->.
275 unsigned buildSExpr(Expr *Exp, CallingContext* CallCtx, int* NDeref = 0) {
276 if (!Exp)
277 return 0;
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000278
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000279 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
280 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000281 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
282 if (PV) {
283 FunctionDecl *FD =
284 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
285 unsigned i = PV->getFunctionScopeIndex();
286
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000287 if (CallCtx && CallCtx->FunArgs &&
288 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000289 // Substitute call arguments for references to function parameters
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000290 assert(i < CallCtx->NumArgs);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000291 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000292 }
293 // Map the param back to the param of the original function declaration.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000294 makeNamedVar(FD->getParamDecl(i));
295 return 1;
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000296 }
297 // Not a function parameter -- just store the reference.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000298 makeNamedVar(ND);
299 return 1;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000300 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000301 // Substitute parent for 'this'
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000302 if (CallCtx && CallCtx->SelfArg) {
303 if (!CallCtx->SelfArrow && NDeref)
304 // 'this' is a pointer, but self is not, so need to take address.
305 --(*NDeref);
306 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
307 }
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000308 else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000309 makeThis();
310 return 1;
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000311 }
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000312 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
313 NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000314 int ImplicitDeref = ME->isArrow() ? 1 : 0;
315 unsigned Root = makeDot(ND, false);
316 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
317 NodeVec[Root].setArrow(ImplicitDeref > 0);
318 NodeVec[Root].setSize(Sz + 1);
319 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000320 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000321 // When calling a function with a lock_returned attribute, replace
322 // the function call with the expression in lock_returned.
DeLesley Hutchins54081532012-08-31 22:09:53 +0000323 CXXMethodDecl* MD =
324 cast<CXXMethodDecl>(CMCE->getMethodDecl()->getMostRecentDecl());
325 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000326 CallingContext LRCallCtx(CMCE->getMethodDecl());
327 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000328 LRCallCtx.SelfArrow =
329 dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000330 LRCallCtx.NumArgs = CMCE->getNumArgs();
331 LRCallCtx.FunArgs = CMCE->getArgs();
332 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000333 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000334 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000335 // Hack to treat smart pointers and iterators as pointers;
336 // ignore any method named get().
337 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
338 CMCE->getNumArgs() == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000339 if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
340 ++(*NDeref);
341 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000342 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000343 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchins186af2d2012-09-20 22:18:02 +0000344 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000345 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000346 Expr** CallArgs = CMCE->getArgs();
347 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000348 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000349 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000350 NodeVec[Root].setSize(Sz + 1);
351 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000352 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
DeLesley Hutchins54081532012-08-31 22:09:53 +0000353 FunctionDecl* FD =
354 cast<FunctionDecl>(CE->getDirectCallee()->getMostRecentDecl());
355 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000356 CallingContext LRCallCtx(CE->getDirectCallee());
357 LRCallCtx.NumArgs = CE->getNumArgs();
358 LRCallCtx.FunArgs = CE->getArgs();
359 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000360 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000361 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000362 // Treat smart pointers and iterators as pointers;
363 // ignore the * and -> operators.
364 if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
365 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000366 if (k == OO_Star) {
367 if (NDeref) ++(*NDeref);
368 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
369 }
370 else if (k == OO_Arrow) {
371 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000372 }
373 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000374 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000375 unsigned Root = makeCall(NumCallArgs, 0);
376 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000377 Expr** CallArgs = CE->getArgs();
378 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000379 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000380 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000381 NodeVec[Root].setSize(Sz+1);
382 return Sz+1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000383 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000384 unsigned Root = makeBinary();
385 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
386 Sz += buildSExpr(BOE->getRHS(), CallCtx);
387 NodeVec[Root].setSize(Sz);
388 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000389 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000390 // Ignore & and * operators -- they're no-ops.
391 // However, we try to figure out whether the expression is a pointer,
392 // so we can use . and -> appropriately in error messages.
393 if (UOE->getOpcode() == UO_Deref) {
394 if (NDeref) ++(*NDeref);
395 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
396 }
397 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000398 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
399 if (DRE->getDecl()->isCXXInstanceMember()) {
400 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
401 // We interpret this syntax specially, as a wildcard.
402 unsigned Root = makeDot(DRE->getDecl(), false);
403 makeWildcard();
404 NodeVec[Root].setSize(2);
405 return 2;
406 }
407 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000408 if (NDeref) --(*NDeref);
409 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
410 }
411 unsigned Root = makeUnary();
412 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
413 NodeVec[Root].setSize(Sz);
414 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000415 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000416 unsigned Root = makeIndex();
417 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
418 Sz += buildSExpr(ASE->getIdx(), CallCtx);
419 NodeVec[Root].setSize(Sz);
420 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000421 } else if (AbstractConditionalOperator *CE =
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000422 dyn_cast<AbstractConditionalOperator>(Exp)) {
423 unsigned Root = makeUnknown(3);
424 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
425 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
426 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
427 NodeVec[Root].setSize(Sz);
428 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000429 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000430 unsigned Root = makeUnknown(3);
431 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
432 Sz += buildSExpr(CE->getLHS(), CallCtx);
433 Sz += buildSExpr(CE->getRHS(), CallCtx);
434 NodeVec[Root].setSize(Sz);
435 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000436 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000437 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000438 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000439 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000440 } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000441 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000442 } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000443 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000444 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000445 isa<CXXNullPtrLiteralExpr>(Exp) ||
446 isa<GNUNullExpr>(Exp) ||
447 isa<CXXBoolLiteralExpr>(Exp) ||
448 isa<FloatingLiteral>(Exp) ||
449 isa<ImaginaryLiteral>(Exp) ||
450 isa<IntegerLiteral>(Exp) ||
451 isa<StringLiteral>(Exp) ||
452 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000453 makeNop();
454 return 1; // FIXME: Ignore literals for now
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000455 } else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000456 makeNop();
457 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000458 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000459 }
460
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000461 /// \brief Construct a SExpr from an expression.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000462 /// \param MutexExp The original mutex expression within an attribute
463 /// \param DeclExp An expression involving the Decl on which the attribute
464 /// occurs.
465 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000466 void buildSExprFromExpr(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000467 CallingContext CallCtx(D);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000468
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000469 if (MutexExp) {
470 if (StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
471 if (SLit->getString() == StringRef("*"))
472 // The "*" expr is a universal lock, which essentially turns off
473 // checks until it is removed from the lockset.
474 makeUniversal();
475 else
476 // Ignore other string literals for now.
477 makeNop();
478 return;
479 }
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000480 }
481
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000482 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000483 if (DeclExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000484 buildSExpr(MutexExp, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000485 return;
486 }
487
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000488 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000489 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000490 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000491 CallCtx.SelfArg = ME->getBase();
492 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000493 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000494 CallCtx.SelfArg = CE->getImplicitObjectArgument();
495 CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
496 CallCtx.NumArgs = CE->getNumArgs();
497 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsdf497822011-12-29 00:56:48 +0000498 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000499 CallCtx.NumArgs = CE->getNumArgs();
500 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000501 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000502 CallCtx.SelfArg = 0; // FIXME -- get the parent from DeclStmt
503 CallCtx.NumArgs = CE->getNumArgs();
504 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins6db51f72011-10-21 20:51:27 +0000505 } else if (D && isa<CXXDestructorDecl>(D)) {
506 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000507 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000508 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000509
510 // If the attribute has no arguments, then assume the argument is "this".
511 if (MutexExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000512 buildSExpr(CallCtx.SelfArg, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000513 return;
514 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000515
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000516 // For most attributes.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000517 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000518 }
519
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000520 /// \brief Get index of next sibling of node i.
521 unsigned getNextSibling(unsigned i) const {
522 return i + NodeVec[i].size();
523 }
524
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000525public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000526 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000527
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000528 /// \param MutexExp The original mutex expression within an attribute
529 /// \param DeclExp An expression involving the Decl on which the attribute
530 /// occurs.
531 /// \param D The declaration to which the lock/unlock attribute is attached.
532 /// Caller must check isValid() after construction.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000533 SExpr(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
534 buildSExprFromExpr(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000535 }
536
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000537 /// Return true if this is a valid decl sequence.
538 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000539 bool isValid() const {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000540 return !NodeVec.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000541 }
542
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000543 bool shouldIgnore() const {
544 // Nop is a mutex that we have decided to deliberately ignore.
545 assert(NodeVec.size() > 0 && "Invalid Mutex");
546 return NodeVec[0].kind() == EOP_Nop;
547 }
548
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000549 bool isUniversal() const {
550 assert(NodeVec.size() > 0 && "Invalid Mutex");
551 return NodeVec[0].kind() == EOP_Universal;
552 }
553
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000554 /// Issue a warning about an invalid lock expression
555 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
556 Expr *DeclExp, const NamedDecl* D) {
557 SourceLocation Loc;
558 if (DeclExp)
559 Loc = DeclExp->getExprLoc();
560
561 // FIXME: add a note about the attribute location in MutexExp or D
562 if (Loc.isValid())
563 Handler.handleInvalidLockExp(Loc);
564 }
565
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000566 bool operator==(const SExpr &other) const {
567 return NodeVec == other.NodeVec;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000568 }
569
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000570 bool operator!=(const SExpr &other) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000571 return !(*this == other);
572 }
573
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000574 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
575 if (NodeVec[i].matches(Other.NodeVec[j])) {
DeLesley Hutchinsf9ee0ba2012-09-11 23:04:49 +0000576 unsigned ni = NodeVec[i].arity();
577 unsigned nj = Other.NodeVec[j].arity();
578 unsigned n = (ni < nj) ? ni : nj;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000579 bool Result = true;
580 unsigned ci = i+1; // first child of i
581 unsigned cj = j+1; // first child of j
582 for (unsigned k = 0; k < n;
583 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
584 Result = Result && matches(Other, ci, cj);
585 }
586 return Result;
587 }
588 return false;
589 }
590
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000591 // A partial match between a.mu and b.mu returns true a and b have the same
592 // type (and thus mu refers to the same mutex declaration), regardless of
593 // whether a and b are different objects or not.
594 bool partiallyMatches(const SExpr &Other) const {
595 if (NodeVec[0].kind() == EOP_Dot)
596 return NodeVec[0].matches(Other.NodeVec[0]);
597 return false;
598 }
599
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000600 /// \brief Pretty print a lock expression for use in error messages.
601 std::string toString(unsigned i = 0) const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000602 assert(isValid());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000603 if (i >= NodeVec.size())
604 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000605
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000606 const SExprNode* N = &NodeVec[i];
607 switch (N->kind()) {
608 case EOP_Nop:
609 return "_";
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000610 case EOP_Wildcard:
611 return "(?)";
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000612 case EOP_Universal:
613 return "*";
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000614 case EOP_This:
615 return "this";
616 case EOP_NVar:
617 case EOP_LVar: {
618 return N->getNamedDecl()->getNameAsString();
619 }
620 case EOP_Dot: {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000621 if (NodeVec[i+1].kind() == EOP_Wildcard) {
622 std::string S = "&";
623 S += N->getNamedDecl()->getQualifiedNameAsString();
624 return S;
625 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000626 std::string FieldName = N->getNamedDecl()->getNameAsString();
627 if (NodeVec[i+1].kind() == EOP_This)
628 return FieldName;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000629
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000630 std::string S = toString(i+1);
631 if (N->isArrow())
632 return S + "->" + FieldName;
633 else
634 return S + "." + FieldName;
635 }
636 case EOP_Call: {
637 std::string S = toString(i+1) + "(";
638 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000639 unsigned ci = getNextSibling(i+1);
640 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000641 S += toString(ci);
642 if (k+1 < NumArgs) S += ",";
643 }
644 S += ")";
645 return S;
646 }
647 case EOP_MCall: {
648 std::string S = "";
649 if (NodeVec[i+1].kind() != EOP_This)
650 S = toString(i+1) + ".";
651 if (const NamedDecl *D = N->getFunctionDecl())
652 S += D->getNameAsString() + "(";
653 else
654 S += "#(";
655 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000656 unsigned ci = getNextSibling(i+1);
657 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000658 S += toString(ci);
659 if (k+1 < NumArgs) S += ",";
660 }
661 S += ")";
662 return S;
663 }
664 case EOP_Index: {
665 std::string S1 = toString(i+1);
666 std::string S2 = toString(i+1 + NodeVec[i+1].size());
667 return S1 + "[" + S2 + "]";
668 }
669 case EOP_Unary: {
670 std::string S = toString(i+1);
671 return "#" + S;
672 }
673 case EOP_Binary: {
674 std::string S1 = toString(i+1);
675 std::string S2 = toString(i+1 + NodeVec[i+1].size());
676 return "(" + S1 + "#" + S2 + ")";
677 }
678 case EOP_Unknown: {
679 unsigned NumChildren = N->arity();
680 if (NumChildren == 0)
681 return "(...)";
682 std::string S = "(";
683 unsigned ci = i+1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000684 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000685 S += toString(ci);
686 if (j+1 < NumChildren) S += "#";
687 }
688 S += ")";
689 return S;
690 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000691 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000692 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000693 }
694};
695
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000696
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000697
698/// \brief A short list of SExprs
699class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000700public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000701 /// \brief Return true if the list contains the specified SExpr
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000702 /// Performs a linear search, because these lists are almost always very small.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000703 bool contains(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000704 for (iterator I=begin(),E=end(); I != E; ++I)
705 if ((*I) == M) return true;
706 return false;
707 }
708
709 /// \brief Push M onto list, bud discard duplicates
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000710 void push_back_nodup(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000711 if (!contains(M)) push_back(M);
712 }
713};
714
715
716
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000717/// \brief This is a helper class that stores info about the most recent
718/// accquire of a Lock.
719///
720/// The main body of the analysis maps MutexIDs to LockDatas.
721struct LockData {
722 SourceLocation AcquireLoc;
723
724 /// \brief LKind stores whether a lock is held shared or exclusively.
725 /// Note that this analysis does not currently support either re-entrant
726 /// locking or lock "upgrading" and "downgrading" between exclusive and
727 /// shared.
728 ///
729 /// FIXME: add support for re-entrant locking and lock up/downgrading
730 LockKind LKind;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000731 bool Managed; // for ScopedLockable objects
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000732 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000733
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000734 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
735 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
736 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000737 {}
738
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000739 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000740 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
741 UnderlyingMutex(Mu)
742 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000743
744 bool operator==(const LockData &other) const {
745 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
746 }
747
748 bool operator!=(const LockData &other) const {
749 return !(*this == other);
750 }
751
752 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000753 ID.AddInteger(AcquireLoc.getRawEncoding());
754 ID.AddInteger(LKind);
755 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000756
757 bool isAtLeast(LockKind LK) {
758 return (LK == LK_Shared) || (LKind == LK_Exclusive);
759 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000760};
761
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000762
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000763/// \brief A FactEntry stores a single fact that is known at a particular point
764/// in the program execution. Currently, this is information regarding a lock
765/// that is held at that point.
766struct FactEntry {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000767 SExpr MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000768 LockData LDat;
769
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000770 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000771 : MutID(M), LDat(L)
772 { }
773};
774
775
776typedef unsigned short FactID;
777
778/// \brief FactManager manages the memory for all facts that are created during
779/// the analysis of a single routine.
780class FactManager {
781private:
782 std::vector<FactEntry> Facts;
783
784public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000785 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000786 Facts.push_back(FactEntry(M,L));
787 return static_cast<unsigned short>(Facts.size() - 1);
788 }
789
790 const FactEntry& operator[](FactID F) const { return Facts[F]; }
791 FactEntry& operator[](FactID F) { return Facts[F]; }
792};
793
794
795/// \brief A FactSet is the set of facts that are known to be true at a
796/// particular program point. FactSets must be small, because they are
797/// frequently copied, and are thus implemented as a set of indices into a
798/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
799/// locks, so we can get away with doing a linear search for lookup. Note
800/// that a hashtable or map is inappropriate in this case, because lookups
801/// may involve partial pattern matches, rather than exact matches.
802class FactSet {
803private:
804 typedef SmallVector<FactID, 4> FactVec;
805
806 FactVec FactIDs;
807
808public:
809 typedef FactVec::iterator iterator;
810 typedef FactVec::const_iterator const_iterator;
811
812 iterator begin() { return FactIDs.begin(); }
813 const_iterator begin() const { return FactIDs.begin(); }
814
815 iterator end() { return FactIDs.end(); }
816 const_iterator end() const { return FactIDs.end(); }
817
818 bool isEmpty() const { return FactIDs.size() == 0; }
819
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000820 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000821 FactID F = FM.newLock(M, L);
822 FactIDs.push_back(F);
823 return F;
824 }
825
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000826 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000827 unsigned n = FactIDs.size();
828 if (n == 0)
829 return false;
830
831 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000832 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000833 FactIDs[i] = FactIDs[n-1];
834 FactIDs.pop_back();
835 return true;
836 }
837 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000838 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000839 FactIDs.pop_back();
840 return true;
841 }
842 return false;
843 }
844
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000845 LockData* findLock(FactManager &FM, const SExpr &M) const {
Chad Rosier2de47702012-09-07 18:44:15 +0000846 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier589190b2012-09-07 19:49:55 +0000847 const SExpr &Exp = FM[*I].MutID;
Chad Rosier2de47702012-09-07 18:44:15 +0000848 if (Exp.matches(M))
849 return &FM[*I].LDat;
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000850 }
851 return 0;
852 }
853
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000854 LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
Chad Rosier2de47702012-09-07 18:44:15 +0000855 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier589190b2012-09-07 19:49:55 +0000856 const SExpr &Exp = FM[*I].MutID;
Chad Rosier2de47702012-09-07 18:44:15 +0000857 if (Exp.matches(M) || Exp.isUniversal())
858 return &FM[*I].LDat;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000859 }
860 return 0;
861 }
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000862
863 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
864 for (const_iterator I=begin(), E=end(); I != E; ++I) {
865 const SExpr& Exp = FM[*I].MutID;
866 if (Exp.partiallyMatches(M)) return &FM[*I];
867 }
868 return 0;
869 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000870};
871
872
873
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000874/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000875/// been locked.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000876typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000877typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000878
879class LocalVariableMap;
880
Richard Smith2e515622012-02-03 04:45:26 +0000881/// A side (entry or exit) of a CFG node.
882enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000883
884/// CFGBlockInfo is a struct which contains all the information that is
885/// maintained for each block in the CFG. See LocalVariableMap for more
886/// information about the contexts.
887struct CFGBlockInfo {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000888 FactSet EntrySet; // Lockset held at entry to block
889 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000890 LocalVarContext EntryContext; // Context held at entry to block
891 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith2e515622012-02-03 04:45:26 +0000892 SourceLocation EntryLoc; // Location of first statement in block
893 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000894 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +0000895 bool Reachable; // Is this block reachable?
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000896
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000897 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith2e515622012-02-03 04:45:26 +0000898 return Side == CBS_Entry ? EntrySet : ExitSet;
899 }
900 SourceLocation getLocation(CFGBlockSide Side) const {
901 return Side == CBS_Entry ? EntryLoc : ExitLoc;
902 }
903
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000904private:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000905 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +0000906 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000907 { }
908
909public:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000910 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000911};
912
913
914
915// A LocalVariableMap maintains a map from local variables to their currently
916// valid definitions. It provides SSA-like functionality when traversing the
917// CFG. Like SSA, each definition or assignment to a variable is assigned a
918// unique name (an integer), which acts as the SSA name for that definition.
919// The total set of names is shared among all CFG basic blocks.
920// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
921// with their SSA-names. Instead, we compute a Context for each point in the
922// code, which maps local variables to the appropriate SSA-name. This map
923// changes with each assignment.
924//
925// The map is computed in a single pass over the CFG. Subsequent analyses can
926// then query the map to find the appropriate Context for a statement, and use
927// that Context to look up the definitions of variables.
928class LocalVariableMap {
929public:
930 typedef LocalVarContext Context;
931
932 /// A VarDefinition consists of an expression, representing the value of the
933 /// variable, along with the context in which that expression should be
934 /// interpreted. A reference VarDefinition does not itself contain this
935 /// information, but instead contains a pointer to a previous VarDefinition.
936 struct VarDefinition {
937 public:
938 friend class LocalVariableMap;
939
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000940 const NamedDecl *Dec; // The original declaration for this variable.
941 const Expr *Exp; // The expression for this variable, OR
942 unsigned Ref; // Reference to another VarDefinition
943 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000944
945 bool isReference() { return !Exp; }
946
947 private:
948 // Create ordinary variable definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000949 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000950 : Dec(D), Exp(E), Ref(0), Ctx(C)
951 { }
952
953 // Create reference to previous definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000954 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000955 : Dec(D), Exp(0), Ref(R), Ctx(C)
956 { }
957 };
958
959private:
960 Context::Factory ContextFactory;
961 std::vector<VarDefinition> VarDefinitions;
962 std::vector<unsigned> CtxIndices;
963 std::vector<std::pair<Stmt*, Context> > SavedContexts;
964
965public:
966 LocalVariableMap() {
967 // index 0 is a placeholder for undefined variables (aka phi-nodes).
968 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
969 }
970
971 /// Look up a definition, within the given context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000972 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000973 const unsigned *i = Ctx.lookup(D);
974 if (!i)
975 return 0;
976 assert(*i < VarDefinitions.size());
977 return &VarDefinitions[*i];
978 }
979
980 /// Look up the definition for D within the given context. Returns
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000981 /// NULL if the expression is not statically known. If successful, also
982 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000983 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000984 const unsigned *P = Ctx.lookup(D);
985 if (!P)
986 return 0;
987
988 unsigned i = *P;
989 while (i > 0) {
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000990 if (VarDefinitions[i].Exp) {
991 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000992 return VarDefinitions[i].Exp;
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000993 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000994 i = VarDefinitions[i].Ref;
995 }
996 return 0;
997 }
998
999 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
1000
1001 /// Return the next context after processing S. This function is used by
1002 /// clients of the class to get the appropriate context when traversing the
1003 /// CFG. It must be called for every assignment or DeclStmt.
1004 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1005 if (SavedContexts[CtxIndex+1].first == S) {
1006 CtxIndex++;
1007 Context Result = SavedContexts[CtxIndex].second;
1008 return Result;
1009 }
1010 return C;
1011 }
1012
1013 void dumpVarDefinitionName(unsigned i) {
1014 if (i == 0) {
1015 llvm::errs() << "Undefined";
1016 return;
1017 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001018 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001019 if (!Dec) {
1020 llvm::errs() << "<<NULL>>";
1021 return;
1022 }
1023 Dec->printName(llvm::errs());
Roman Divacky31ba6132012-09-06 15:59:27 +00001024 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001025 }
1026
1027 /// Dumps an ASCII representation of the variable map to llvm::errs()
1028 void dump() {
1029 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001030 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001031 unsigned Ref = VarDefinitions[i].Ref;
1032
1033 dumpVarDefinitionName(i);
1034 llvm::errs() << " = ";
1035 if (Exp) Exp->dump();
1036 else {
1037 dumpVarDefinitionName(Ref);
1038 llvm::errs() << "\n";
1039 }
1040 }
1041 }
1042
1043 /// Dumps an ASCII representation of a Context to llvm::errs()
1044 void dumpContext(Context C) {
1045 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001046 const NamedDecl *D = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001047 D->printName(llvm::errs());
1048 const unsigned *i = C.lookup(D);
1049 llvm::errs() << " -> ";
1050 dumpVarDefinitionName(*i);
1051 llvm::errs() << "\n";
1052 }
1053 }
1054
1055 /// Builds the variable map.
1056 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
1057 std::vector<CFGBlockInfo> &BlockInfo);
1058
1059protected:
1060 // Get the current context index
1061 unsigned getContextIndex() { return SavedContexts.size()-1; }
1062
1063 // Save the current context for later replay
1064 void saveContext(Stmt *S, Context C) {
1065 SavedContexts.push_back(std::make_pair(S,C));
1066 }
1067
1068 // Adds a new definition to the given context, and returns a new context.
1069 // This method should be called when declaring a new variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001070 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001071 assert(!Ctx.contains(D));
1072 unsigned newID = VarDefinitions.size();
1073 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1074 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1075 return NewCtx;
1076 }
1077
1078 // Add a new reference to an existing definition.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001079 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001080 unsigned newID = VarDefinitions.size();
1081 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1082 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1083 return NewCtx;
1084 }
1085
1086 // Updates a definition only if that definition is already in the map.
1087 // This method should be called when assigning to an existing variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001088 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001089 if (Ctx.contains(D)) {
1090 unsigned newID = VarDefinitions.size();
1091 Context NewCtx = ContextFactory.remove(Ctx, D);
1092 NewCtx = ContextFactory.add(NewCtx, D, newID);
1093 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1094 return NewCtx;
1095 }
1096 return Ctx;
1097 }
1098
1099 // Removes a definition from the context, but keeps the variable name
1100 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001101 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001102 Context NewCtx = Ctx;
1103 if (NewCtx.contains(D)) {
1104 NewCtx = ContextFactory.remove(NewCtx, D);
1105 NewCtx = ContextFactory.add(NewCtx, D, 0);
1106 }
1107 return NewCtx;
1108 }
1109
1110 // Remove a definition entirely frmo the context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001111 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001112 Context NewCtx = Ctx;
1113 if (NewCtx.contains(D)) {
1114 NewCtx = ContextFactory.remove(NewCtx, D);
1115 }
1116 return NewCtx;
1117 }
1118
1119 Context intersectContexts(Context C1, Context C2);
1120 Context createReferenceContext(Context C);
1121 void intersectBackEdge(Context C1, Context C2);
1122
1123 friend class VarMapBuilder;
1124};
1125
1126
1127// This has to be defined after LocalVariableMap.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001128CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1129 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001130}
1131
1132
1133/// Visitor which builds a LocalVariableMap
1134class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1135public:
1136 LocalVariableMap* VMap;
1137 LocalVariableMap::Context Ctx;
1138
1139 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1140 : VMap(VM), Ctx(C) {}
1141
1142 void VisitDeclStmt(DeclStmt *S);
1143 void VisitBinaryOperator(BinaryOperator *BO);
1144};
1145
1146
1147// Add new local variables to the variable map
1148void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1149 bool modifiedCtx = false;
1150 DeclGroupRef DGrp = S->getDeclGroup();
1151 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1152 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1153 Expr *E = VD->getInit();
1154
1155 // Add local variables with trivial type to the variable map
1156 QualType T = VD->getType();
1157 if (T.isTrivialType(VD->getASTContext())) {
1158 Ctx = VMap->addDefinition(VD, E, Ctx);
1159 modifiedCtx = true;
1160 }
1161 }
1162 }
1163 if (modifiedCtx)
1164 VMap->saveContext(S, Ctx);
1165}
1166
1167// Update local variable definitions in variable map
1168void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1169 if (!BO->isAssignmentOp())
1170 return;
1171
1172 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1173
1174 // Update the variable map and current context.
1175 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1176 ValueDecl *VDec = DRE->getDecl();
1177 if (Ctx.lookup(VDec)) {
1178 if (BO->getOpcode() == BO_Assign)
1179 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1180 else
1181 // FIXME -- handle compound assignment operators
1182 Ctx = VMap->clearDefinition(VDec, Ctx);
1183 VMap->saveContext(BO, Ctx);
1184 }
1185 }
1186}
1187
1188
1189// Computes the intersection of two contexts. The intersection is the
1190// set of variables which have the same definition in both contexts;
1191// variables with different definitions are discarded.
1192LocalVariableMap::Context
1193LocalVariableMap::intersectContexts(Context C1, Context C2) {
1194 Context Result = C1;
1195 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001196 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001197 unsigned i1 = I.getData();
1198 const unsigned *i2 = C2.lookup(Dec);
1199 if (!i2) // variable doesn't exist on second path
1200 Result = removeDefinition(Dec, Result);
1201 else if (*i2 != i1) // variable exists, but has different definition
1202 Result = clearDefinition(Dec, Result);
1203 }
1204 return Result;
1205}
1206
1207// For every variable in C, create a new variable that refers to the
1208// definition in C. Return a new context that contains these new variables.
1209// (We use this for a naive implementation of SSA on loop back-edges.)
1210LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1211 Context Result = getEmptyContext();
1212 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001213 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001214 unsigned i = I.getData();
1215 Result = addReference(Dec, i, Result);
1216 }
1217 return Result;
1218}
1219
1220// This routine also takes the intersection of C1 and C2, but it does so by
1221// altering the VarDefinitions. C1 must be the result of an earlier call to
1222// createReferenceContext.
1223void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1224 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001225 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001226 unsigned i1 = I.getData();
1227 VarDefinition *VDef = &VarDefinitions[i1];
1228 assert(VDef->isReference());
1229
1230 const unsigned *i2 = C2.lookup(Dec);
1231 if (!i2 || (*i2 != i1))
1232 VDef->Ref = 0; // Mark this variable as undefined
1233 }
1234}
1235
1236
1237// Traverse the CFG in topological order, so all predecessors of a block
1238// (excluding back-edges) are visited before the block itself. At
1239// each point in the code, we calculate a Context, which holds the set of
1240// variable definitions which are visible at that point in execution.
1241// Visible variables are mapped to their definitions using an array that
1242// contains all definitions.
1243//
1244// At join points in the CFG, the set is computed as the intersection of
1245// the incoming sets along each edge, E.g.
1246//
1247// { Context | VarDefinitions }
1248// int x = 0; { x -> x1 | x1 = 0 }
1249// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1250// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1251// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1252// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1253//
1254// This is essentially a simpler and more naive version of the standard SSA
1255// algorithm. Those definitions that remain in the intersection are from blocks
1256// that strictly dominate the current block. We do not bother to insert proper
1257// phi nodes, because they are not used in our analysis; instead, wherever
1258// a phi node would be required, we simply remove that definition from the
1259// context (E.g. x above).
1260//
1261// The initial traversal does not capture back-edges, so those need to be
1262// handled on a separate pass. Whenever the first pass encounters an
1263// incoming back edge, it duplicates the context, creating new definitions
1264// that refer back to the originals. (These correspond to places where SSA
1265// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001266// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001267// node was actually required.) E.g.
1268//
1269// { Context | VarDefinitions }
1270// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1271// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1272// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1273// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1274//
1275void LocalVariableMap::traverseCFG(CFG *CFGraph,
1276 PostOrderCFGView *SortedGraph,
1277 std::vector<CFGBlockInfo> &BlockInfo) {
1278 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1279
1280 CtxIndices.resize(CFGraph->getNumBlockIDs());
1281
1282 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1283 E = SortedGraph->end(); I!= E; ++I) {
1284 const CFGBlock *CurrBlock = *I;
1285 int CurrBlockID = CurrBlock->getBlockID();
1286 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1287
1288 VisitedBlocks.insert(CurrBlock);
1289
1290 // Calculate the entry context for the current block
1291 bool HasBackEdges = false;
1292 bool CtxInit = true;
1293 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1294 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1295 // if *PI -> CurrBlock is a back edge, so skip it
1296 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1297 HasBackEdges = true;
1298 continue;
1299 }
1300
1301 int PrevBlockID = (*PI)->getBlockID();
1302 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1303
1304 if (CtxInit) {
1305 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1306 CtxInit = false;
1307 }
1308 else {
1309 CurrBlockInfo->EntryContext =
1310 intersectContexts(CurrBlockInfo->EntryContext,
1311 PrevBlockInfo->ExitContext);
1312 }
1313 }
1314
1315 // Duplicate the context if we have back-edges, so we can call
1316 // intersectBackEdges later.
1317 if (HasBackEdges)
1318 CurrBlockInfo->EntryContext =
1319 createReferenceContext(CurrBlockInfo->EntryContext);
1320
1321 // Create a starting context index for the current block
1322 saveContext(0, CurrBlockInfo->EntryContext);
1323 CurrBlockInfo->EntryIndex = getContextIndex();
1324
1325 // Visit all the statements in the basic block.
1326 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1327 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1328 BE = CurrBlock->end(); BI != BE; ++BI) {
1329 switch (BI->getKind()) {
1330 case CFGElement::Statement: {
1331 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1332 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1333 break;
1334 }
1335 default:
1336 break;
1337 }
1338 }
1339 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1340
1341 // Mark variables on back edges as "unknown" if they've been changed.
1342 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1343 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1344 // if CurrBlock -> *SI is *not* a back edge
1345 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1346 continue;
1347
1348 CFGBlock *FirstLoopBlock = *SI;
1349 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1350 Context LoopEnd = CurrBlockInfo->ExitContext;
1351 intersectBackEdge(LoopBegin, LoopEnd);
1352 }
1353 }
1354
1355 // Put an extra entry at the end of the indexed context array
1356 unsigned exitID = CFGraph->getExit().getBlockID();
1357 saveContext(0, BlockInfo[exitID].ExitContext);
1358}
1359
Richard Smith2e515622012-02-03 04:45:26 +00001360/// Find the appropriate source locations to use when producing diagnostics for
1361/// each block in the CFG.
1362static void findBlockLocations(CFG *CFGraph,
1363 PostOrderCFGView *SortedGraph,
1364 std::vector<CFGBlockInfo> &BlockInfo) {
1365 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1366 E = SortedGraph->end(); I!= E; ++I) {
1367 const CFGBlock *CurrBlock = *I;
1368 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1369
1370 // Find the source location of the last statement in the block, if the
1371 // block is not empty.
1372 if (const Stmt *S = CurrBlock->getTerminator()) {
1373 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1374 } else {
1375 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1376 BE = CurrBlock->rend(); BI != BE; ++BI) {
1377 // FIXME: Handle other CFGElement kinds.
1378 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1379 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1380 break;
1381 }
1382 }
1383 }
1384
1385 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1386 // This block contains at least one statement. Find the source location
1387 // of the first statement in the block.
1388 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1389 BE = CurrBlock->end(); BI != BE; ++BI) {
1390 // FIXME: Handle other CFGElement kinds.
1391 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1392 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1393 break;
1394 }
1395 }
1396 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1397 CurrBlock != &CFGraph->getExit()) {
1398 // The block is empty, and has a single predecessor. Use its exit
1399 // location.
1400 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1401 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1402 }
1403 }
1404}
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001405
1406/// \brief Class which implements the core thread safety analysis routines.
1407class ThreadSafetyAnalyzer {
1408 friend class BuildLockset;
1409
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001410 ThreadSafetyHandler &Handler;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001411 LocalVariableMap LocalVarMap;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001412 FactManager FactMan;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001413 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001414
1415public:
1416 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1417
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001418 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1419 void removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001420 SourceLocation UnlockLoc, bool FullyRemove=false);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001421
1422 template <typename AttrType>
1423 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1424 const NamedDecl *D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001425
1426 template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001427 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1428 const NamedDecl *D,
1429 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1430 Expr *BrE, bool Neg);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001431
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001432 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1433 bool &Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001434
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001435 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1436 const CFGBlock* PredBlock,
1437 const CFGBlock *CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001438
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001439 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1440 SourceLocation JoinLoc,
1441 LockErrorKind LEK1, LockErrorKind LEK2,
1442 bool Modify=true);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001443
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001444 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1445 SourceLocation JoinLoc, LockErrorKind LEK1,
1446 bool Modify=true) {
1447 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001448 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001449
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001450 void runAnalysis(AnalysisDeclContext &AC);
1451};
1452
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001453
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001454/// \brief Add a new lock to the lockset, warning if the lock is already there.
1455/// \param Mutex -- the Mutex expression for the lock
1456/// \param LDat -- the LockData for the lock
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001457void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001458 const LockData &LDat) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001459 // FIXME: deal with acquired before/after annotations.
1460 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001461 if (Mutex.shouldIgnore())
1462 return;
1463
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001464 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001465 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001466 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001467 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001468 }
1469}
1470
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001471
1472/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenekad0fe032012-08-22 23:50:41 +00001473/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001474/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001475void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001476 const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001477 SourceLocation UnlockLoc,
1478 bool FullyRemove) {
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001479 if (Mutex.shouldIgnore())
1480 return;
1481
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001482 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001483 if (!LDat) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001484 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001485 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001486 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001487
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001488 if (LDat->UnderlyingMutex.isValid()) {
1489 // This is scoped lockable object, which manages the real mutex.
1490 if (FullyRemove) {
1491 // We're destroying the managing object.
1492 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001493 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1494 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001495 } else {
1496 // We're releasing the underlying mutex, but not destroying the
1497 // managing object. Warn on dual release.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001498 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001499 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001500 UnlockLoc);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001501 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001502 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1503 return;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001504 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001505 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001506 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001507}
1508
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001509
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001510/// \brief Extract the list of mutexIDs from the attribute on an expression,
1511/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001512template <typename AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001513void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1514 Expr *Exp, const NamedDecl *D) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001515 typedef typename AttrType::args_iterator iterator_type;
1516
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001517 if (Attr->args_size() == 0) {
1518 // The mutex held is the "this" object.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001519 SExpr Mu(0, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001520 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001521 SExpr::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001522 else
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001523 Mtxs.push_back_nodup(Mu);
1524 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001525 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001526
1527 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001528 SExpr Mu(*I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001529 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001530 SExpr::warnInvalidLock(Handler, *I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001531 else
1532 Mtxs.push_back_nodup(Mu);
1533 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001534}
1535
1536
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001537/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1538/// trylock applies to the given edge, then push them onto Mtxs, discarding
1539/// any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001540template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001541void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1542 Expr *Exp, const NamedDecl *D,
1543 const CFGBlock *PredBlock,
1544 const CFGBlock *CurrBlock,
1545 Expr *BrE, bool Neg) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001546 // Find out which branch has the lock
1547 bool branch = 0;
1548 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1549 branch = BLE->getValue();
1550 }
1551 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1552 branch = ILE->getValue().getBoolValue();
1553 }
1554 int branchnum = branch ? 0 : 1;
1555 if (Neg) branchnum = !branchnum;
1556
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001557 // If we've taken the trylock branch, then add the lock
1558 int i = 0;
1559 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1560 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1561 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001562 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001563 }
1564 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001565}
1566
1567
DeLesley Hutchins13106112012-07-10 21:47:55 +00001568bool getStaticBooleanValue(Expr* E, bool& TCond) {
1569 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1570 TCond = false;
1571 return true;
1572 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1573 TCond = BLE->getValue();
1574 return true;
1575 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1576 TCond = ILE->getValue().getBoolValue();
1577 return true;
1578 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1579 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1580 }
1581 return false;
1582}
1583
1584
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001585// If Cond can be traced back to a function call, return the call expression.
1586// The negate variable should be called with false, and will be set to true
1587// if the function call is negated, e.g. if (!mu.tryLock(...))
1588const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1589 LocalVarContext C,
1590 bool &Negate) {
1591 if (!Cond)
1592 return 0;
1593
1594 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1595 return CallExp;
1596 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001597 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1598 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1599 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001600 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1601 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1602 }
DeLesley Hutchinsfd0f11c2012-09-05 20:01:16 +00001603 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1604 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1605 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001606 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1607 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1608 return getTrylockCallExpr(E, C, Negate);
1609 }
1610 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1611 if (UOP->getOpcode() == UO_LNot) {
1612 Negate = !Negate;
1613 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1614 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001615 return 0;
1616 }
1617 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1618 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1619 if (BOP->getOpcode() == BO_NE)
1620 Negate = !Negate;
1621
1622 bool TCond = false;
1623 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1624 if (!TCond) Negate = !Negate;
1625 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1626 }
1627 else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1628 if (!TCond) Negate = !Negate;
1629 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1630 }
1631 return 0;
1632 }
1633 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001634 }
1635 // FIXME -- handle && and || as well.
DeLesley Hutchins13106112012-07-10 21:47:55 +00001636 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001637}
1638
1639
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001640/// \brief Find the lockset that holds on the edge between PredBlock
1641/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1642/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001643void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1644 const FactSet &ExitSet,
1645 const CFGBlock *PredBlock,
1646 const CFGBlock *CurrBlock) {
1647 Result = ExitSet;
1648
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001649 if (!PredBlock->getTerminatorCondition())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001650 return;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001651
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001652 bool Negate = false;
1653 const Stmt *Cond = PredBlock->getTerminatorCondition();
1654 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1655 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1656
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001657 CallExpr *Exp =
1658 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001659 if (!Exp)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001660 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001661
1662 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1663 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001664 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001665
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001666
1667 MutexIDList ExclusiveLocksToAdd;
1668 MutexIDList SharedLocksToAdd;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001669
1670 // If the condition is a call to a Trylock function, then grab the attributes
1671 AttrVec &ArgAttrs = FunDecl->getAttrs();
1672 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1673 Attr *Attr = ArgAttrs[i];
1674 switch (Attr->getKind()) {
1675 case attr::ExclusiveTrylockFunction: {
1676 ExclusiveTrylockFunctionAttr *A =
1677 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001678 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1679 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001680 break;
1681 }
1682 case attr::SharedTrylockFunction: {
1683 SharedTrylockFunctionAttr *A =
1684 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchins60ff1982012-09-20 23:14:43 +00001685 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001686 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001687 break;
1688 }
1689 default:
1690 break;
1691 }
1692 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001693
1694 // Add and remove locks.
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001695 SourceLocation Loc = Exp->getExprLoc();
1696 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001697 addLock(Result, ExclusiveLocksToAdd[i],
1698 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001699 }
1700 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001701 addLock(Result, SharedLocksToAdd[i],
1702 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001703 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001704}
1705
1706
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001707/// \brief We use this class to visit different types of expressions in
1708/// CFGBlocks, and build up the lockset.
1709/// An expression may cause us to add or remove locks from the lockset, or else
1710/// output error messages related to missing locks.
1711/// FIXME: In future, we may be able to not inherit from a visitor.
1712class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001713 friend class ThreadSafetyAnalyzer;
1714
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001715 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001716 FactSet FSet;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001717 LocalVariableMap::Context LVarCtx;
1718 unsigned CtxIndex;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001719
1720 // Helper functions
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001721 const ValueDecl *getValueDecl(Expr *Exp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001722
1723 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1724 Expr *MutexExp, ProtectedOperationKind POK);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001725 void warnIfMutexHeld(const NamedDecl *D, Expr *Exp, Expr *MutexExp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001726
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001727 void checkAccess(Expr *Exp, AccessKind AK);
1728 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001729 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001730
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001731public:
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001732 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001733 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001734 Analyzer(Anlzr),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001735 FSet(Info.EntrySet),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001736 LVarCtx(Info.EntryContext),
1737 CtxIndex(Info.EntryIndex)
1738 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001739
1740 void VisitUnaryOperator(UnaryOperator *UO);
1741 void VisitBinaryOperator(BinaryOperator *BO);
1742 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001743 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001744 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001745 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001746};
1747
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001748
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001749/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1750const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1751 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1752 return DR->getDecl();
1753
1754 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1755 return ME->getMemberDecl();
1756
1757 return 0;
1758}
1759
1760/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001761/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001762void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1763 AccessKind AK, Expr *MutexExp,
1764 ProtectedOperationKind POK) {
1765 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001766
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001767 SExpr Mutex(MutexExp, Exp, D);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001768 if (!Mutex.isValid()) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001769 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001770 return;
1771 } else if (Mutex.shouldIgnore()) {
1772 return;
1773 }
1774
1775 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001776 bool NoError = true;
1777 if (!LDat) {
1778 // No exact match found. Look for a partial match.
1779 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1780 if (FEntry) {
1781 // Warn that there's no precise match.
1782 LDat = &FEntry->LDat;
1783 std::string PartMatchStr = FEntry->MutID.toString();
1784 StringRef PartMatchName(PartMatchStr);
1785 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1786 Exp->getExprLoc(), &PartMatchName);
1787 } else {
1788 // Warn that there's no match at all.
1789 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1790 Exp->getExprLoc());
1791 }
1792 NoError = false;
1793 }
1794 // Make sure the mutex we found is the right kind.
1795 if (NoError && LDat && !LDat->isAtLeast(LK))
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001796 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001797 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001798}
1799
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001800/// \brief Warn if the LSet contains the given lock.
1801void BuildLockset::warnIfMutexHeld(const NamedDecl *D, Expr* Exp,
1802 Expr *MutexExp) {
1803 SExpr Mutex(MutexExp, Exp, D);
1804 if (!Mutex.isValid()) {
1805 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
1806 return;
1807 }
1808
1809 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001810 if (LDat) {
1811 std::string DeclName = D->getNameAsString();
1812 StringRef DeclNameSR (DeclName);
1813 Analyzer->Handler.handleFunExcludesLock(DeclNameSR, Mutex.toString(),
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001814 Exp->getExprLoc());
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001815 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001816}
1817
1818
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001819/// \brief This method identifies variable dereferences and checks pt_guarded_by
1820/// and pt_guarded_var annotations. Note that we only check these annotations
1821/// at the time a pointer is dereferenced.
1822/// FIXME: We need to check for other types of pointer dereferences
1823/// (e.g. [], ->) and deal with them here.
1824/// \param Exp An expression that has been read or written.
1825void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1826 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1827 if (!UO || UO->getOpcode() != clang::UO_Deref)
1828 return;
1829 Exp = UO->getSubExpr()->IgnoreParenCasts();
1830
1831 const ValueDecl *D = getValueDecl(Exp);
1832 if(!D || !D->hasAttrs())
1833 return;
1834
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001835 if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001836 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1837 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001838
1839 const AttrVec &ArgAttrs = D->getAttrs();
1840 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1841 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1842 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1843}
1844
1845/// \brief Checks guarded_by and guarded_var attributes.
1846/// Whenever we identify an access (read or write) of a DeclRefExpr or
1847/// MemberExpr, we need to check whether there are any guarded_by or
1848/// guarded_var attributes, and make sure we hold the appropriate mutexes.
1849void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1850 const ValueDecl *D = getValueDecl(Exp);
1851 if(!D || !D->hasAttrs())
1852 return;
1853
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001854 if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001855 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1856 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001857
1858 const AttrVec &ArgAttrs = D->getAttrs();
1859 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1860 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1861 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1862}
1863
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001864/// \brief Process a function call, method call, constructor call,
1865/// or destructor call. This involves looking at the attributes on the
1866/// corresponding function/method/constructor/destructor, issuing warnings,
1867/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001868///
1869/// FIXME: For classes annotated with one of the guarded annotations, we need
1870/// to treat const method calls as reads and non-const method calls as writes,
1871/// and check that the appropriate locks are held. Non-const method calls with
1872/// the same signature as const method calls can be also treated as reads.
1873///
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001874void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1875 const AttrVec &ArgAttrs = D->getAttrs();
1876 MutexIDList ExclusiveLocksToAdd;
1877 MutexIDList SharedLocksToAdd;
1878 MutexIDList LocksToRemove;
1879
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001880 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001881 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1882 switch (At->getKind()) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001883 // When we encounter an exclusive lock function, we need to add the lock
1884 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001885 case attr::ExclusiveLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001886 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1887 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001888 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001889 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001890
1891 // When we encounter a shared lock function, we need to add the lock
1892 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001893 case attr::SharedLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001894 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1895 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001896 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001897 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001898
1899 // When we encounter an unlock function, we need to remove unlocked
1900 // mutexes from the lockset, and flag a warning if they are not there.
1901 case attr::UnlockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001902 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1903 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001904 break;
1905 }
1906
1907 case attr::ExclusiveLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001908 ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001909
1910 for (ExclusiveLocksRequiredAttr::args_iterator
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001911 I = A->args_begin(), E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001912 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1913 break;
1914 }
1915
1916 case attr::SharedLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001917 SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001918
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001919 for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1920 E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001921 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1922 break;
1923 }
1924
1925 case attr::LocksExcluded: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001926 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001927
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001928 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1929 E = A->args_end(); I != E; ++I) {
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001930 warnIfMutexHeld(D, Exp, *I);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001931 }
1932 break;
1933 }
1934
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001935 // Ignore other (non thread-safety) attributes
1936 default:
1937 break;
1938 }
1939 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001940
1941 // Figure out if we're calling the constructor of scoped lockable class
1942 bool isScopedVar = false;
1943 if (VD) {
1944 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1945 const CXXRecordDecl* PD = CD->getParent();
1946 if (PD && PD->getAttr<ScopedLockableAttr>())
1947 isScopedVar = true;
1948 }
1949 }
1950
1951 // Add locks.
1952 SourceLocation Loc = Exp->getExprLoc();
1953 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001954 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
1955 LockData(Loc, LK_Exclusive, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001956 }
1957 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001958 Analyzer->addLock(FSet, SharedLocksToAdd[i],
1959 LockData(Loc, LK_Shared, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001960 }
1961
1962 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1963 // FIXME -- this doesn't work if we acquire multiple locks.
1964 if (isScopedVar) {
1965 SourceLocation MLoc = VD->getLocation();
1966 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001967 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001968
1969 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001970 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
1971 ExclusiveLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001972 }
1973 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001974 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
1975 SharedLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001976 }
1977 }
1978
1979 // Remove locks.
1980 // FIXME -- should only fully remove if the attribute refers to 'this'.
1981 bool Dtor = isa<CXXDestructorDecl>(D);
1982 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001983 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001984 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001985}
1986
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +00001987
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001988/// \brief For unary operations which read and write a variable, we need to
1989/// check whether we hold any required mutexes. Reads are checked in
1990/// VisitCastExpr.
1991void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1992 switch (UO->getOpcode()) {
1993 case clang::UO_PostDec:
1994 case clang::UO_PostInc:
1995 case clang::UO_PreDec:
1996 case clang::UO_PreInc: {
1997 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1998 checkAccess(SubExp, AK_Written);
1999 checkDereference(SubExp, AK_Written);
2000 break;
2001 }
2002 default:
2003 break;
2004 }
2005}
2006
2007/// For binary operations which assign to a variable (writes), we need to check
2008/// whether we hold any required mutexes.
2009/// FIXME: Deal with non-primitive types.
2010void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2011 if (!BO->isAssignmentOp())
2012 return;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002013
2014 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002015 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002016
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00002017 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
2018 checkAccess(LHSExp, AK_Written);
2019 checkDereference(LHSExp, AK_Written);
2020}
2021
2022/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2023/// need to ensure we hold any required mutexes.
2024/// FIXME: Deal with non-primitive types.
2025void BuildLockset::VisitCastExpr(CastExpr *CE) {
2026 if (CE->getCastKind() != CK_LValueToRValue)
2027 return;
2028 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
2029 checkAccess(SubExp, AK_Read);
2030 checkDereference(SubExp, AK_Read);
2031}
2032
2033
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00002034void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00002035 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2036 if(!D || !D->hasAttrs())
2037 return;
2038 handleCall(Exp, D);
2039}
2040
2041void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00002042 // FIXME -- only handles constructors in DeclStmt below.
2043}
2044
2045void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002046 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002047 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002048
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00002049 DeclGroupRef DGrp = S->getDeclGroup();
2050 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2051 Decl *D = *I;
2052 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2053 Expr *E = VD->getInit();
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +00002054 // handle constructors that involve temporaries
2055 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2056 E = EWC->getSubExpr();
2057
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00002058 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2059 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2060 if (!CtorD || !CtorD->hasAttrs())
2061 return;
2062 handleCall(CE, CtorD, VD);
2063 }
2064 }
2065 }
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00002066}
2067
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002068
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002069
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00002070/// \brief Compute the intersection of two locksets and issue warnings for any
2071/// locks in the symmetric difference.
2072///
2073/// This function is used at a merge point in the CFG when comparing the lockset
2074/// of each branch being merged. For example, given the following sequence:
2075/// A; if () then B; else C; D; we need to check that the lockset after B and C
2076/// are the same. In the event of a difference, we use the intersection of these
2077/// two locksets at the start of D.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002078///
Ted Kremenekad0fe032012-08-22 23:50:41 +00002079/// \param FSet1 The first lockset.
2080/// \param FSet2 The second lockset.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002081/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002082/// \param LEK1 The error message to report if a mutex is missing from LSet1
2083/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002084void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2085 const FactSet &FSet2,
2086 SourceLocation JoinLoc,
2087 LockErrorKind LEK1,
2088 LockErrorKind LEK2,
2089 bool Modify) {
2090 FactSet FSet1Orig = FSet1;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002091
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002092 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2093 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002094 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002095 const LockData &LDat2 = FactMan[*I].LDat;
2096
2097 if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002098 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002099 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002100 LDat2.AcquireLoc,
2101 LDat1->AcquireLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002102 if (Modify && LDat1->LKind != LK_Exclusive) {
2103 FSet1.removeLock(FactMan, FSet2Mutex);
2104 FSet1.addLock(FactMan, FSet2Mutex, LDat2);
2105 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002106 }
2107 } else {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002108 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002109 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002110 // If this is a scoped lock that manages another mutex, and if the
2111 // underlying mutex is still held, then warn about the underlying
2112 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002113 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002114 LDat2.AcquireLoc,
2115 JoinLoc, LEK1);
2116 }
2117 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00002118 else if (!LDat2.Managed && !FSet2Mutex.isUniversal())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002119 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002120 LDat2.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002121 JoinLoc, LEK1);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002122 }
2123 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002124
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002125 for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
2126 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002127 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002128 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00002129
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002130 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002131 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002132 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002133 // If this is a scoped lock that manages another mutex, and if the
2134 // underlying mutex is still held, then warn about the underlying
2135 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002136 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002137 LDat1.AcquireLoc,
2138 JoinLoc, LEK1);
2139 }
2140 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00002141 else if (!LDat1.Managed && !FSet1Mutex.isUniversal())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002142 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002143 LDat1.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002144 JoinLoc, LEK2);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002145 if (Modify)
2146 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002147 }
2148 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002149}
2150
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002151
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002152
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002153/// \brief Check a function's CFG for thread-safety violations.
2154///
2155/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2156/// at the end of each block, and issue warnings for thread safety violations.
2157/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002158void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002159 CFG *CFGraph = AC.getCFG();
2160 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002161 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2162
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002163 // AC.dumpCFG(true);
2164
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002165 if (!D)
2166 return; // Ignore anonymous functions for now.
2167 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
2168 return;
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002169 // FIXME: Do something a bit more intelligent inside constructor and
2170 // destructor code. Constructors and destructors must assume unique access
2171 // to 'this', so checks on member variable access is disabled, but we should
2172 // still enable checks on other objects.
2173 if (isa<CXXConstructorDecl>(D))
2174 return; // Don't check inside constructors.
2175 if (isa<CXXDestructorDecl>(D))
2176 return; // Don't check inside destructors.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002177
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002178 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002179 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002180
2181 // We need to explore the CFG via a "topological" ordering.
2182 // That way, we will be guaranteed to have information about required
2183 // predecessor locksets when exploring a new block.
Ted Kremenek439ed162011-10-22 02:14:27 +00002184 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2185 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002186
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +00002187 // Mark entry block as reachable
2188 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2189
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002190 // Compute SSA names for local variables
2191 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2192
Richard Smith2e515622012-02-03 04:45:26 +00002193 // Fill in source locations for all CFGBlocks.
2194 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2195
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002196 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002197 // to initial lockset. Also turn off checking for lock and unlock functions.
2198 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek439ed162011-10-22 02:14:27 +00002199 if (!SortedGraph->empty() && D->hasAttrs()) {
2200 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002201 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002202 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002203
2204 MutexIDList ExclusiveLocksToAdd;
2205 MutexIDList SharedLocksToAdd;
2206
2207 SourceLocation Loc = D->getLocation();
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002208 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002209 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002210 Loc = Attr->getLocation();
2211 if (ExclusiveLocksRequiredAttr *A
2212 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
2213 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2214 } else if (SharedLocksRequiredAttr *A
2215 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
2216 getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002217 } else if (isa<UnlockFunctionAttr>(Attr)) {
2218 // Don't try to check unlock functions for now
2219 return;
2220 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
2221 // Don't try to check lock functions for now
2222 return;
2223 } else if (isa<SharedLockFunctionAttr>(Attr)) {
2224 // Don't try to check lock functions for now
2225 return;
DeLesley Hutchins76f0a6e2012-07-02 21:59:24 +00002226 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2227 // Don't try to check trylock functions for now
2228 return;
2229 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2230 // Don't try to check trylock functions for now
2231 return;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002232 }
2233 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002234
2235 // FIXME -- Loc can be wrong here.
2236 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002237 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2238 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002239 }
2240 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002241 addLock(InitialLockset, SharedLocksToAdd[i],
2242 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002243 }
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002244 }
2245
Ted Kremenek439ed162011-10-22 02:14:27 +00002246 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2247 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002248 const CFGBlock *CurrBlock = *I;
2249 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002250 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002251
2252 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002253 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002254
2255 // Iterate through the predecessor blocks and warn if the lockset for all
2256 // predecessors is not the same. We take the entry lockset of the current
2257 // block to be the intersection of all previous locksets.
2258 // FIXME: By keeping the intersection, we may output more errors in future
2259 // for a lock which is not in the intersection, but was in the union. We
2260 // may want to also keep the union in future. As an example, let's say
2261 // the intersection contains Mutex L, and the union contains L and M.
2262 // Later we unlock M. At this point, we would output an error because we
2263 // never locked M; although the real error is probably that we forgot to
2264 // lock M on all code paths. Conversely, let's say that later we lock M.
2265 // In this case, we should compare against the intersection instead of the
2266 // union because the real error is probably that we forgot to unlock M on
2267 // all code paths.
2268 bool LocksetInitialized = false;
Richard Smithaacde712012-02-03 03:30:07 +00002269 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002270 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2271 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2272
2273 // if *PI -> CurrBlock is a back edge
2274 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2275 continue;
2276
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +00002277 int PrevBlockID = (*PI)->getBlockID();
2278 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2279
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00002280 // Ignore edges from blocks that can't return.
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +00002281 if ((*PI)->hasNoReturnElement() || !PrevBlockInfo->Reachable)
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00002282 continue;
2283
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +00002284 // Okay, we can reach this block from the entry.
2285 CurrBlockInfo->Reachable = true;
2286
Richard Smithaacde712012-02-03 03:30:07 +00002287 // If the previous block ended in a 'continue' or 'break' statement, then
2288 // a difference in locksets is probably due to a bug in that block, rather
2289 // than in some other predecessor. In that case, keep the other
2290 // predecessor's lockset.
2291 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2292 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2293 SpecialBlocks.push_back(*PI);
2294 continue;
2295 }
2296 }
2297
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +00002298
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002299 FactSet PrevLockset;
2300 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002301
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002302 if (!LocksetInitialized) {
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002303 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002304 LocksetInitialized = true;
2305 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002306 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2307 CurrBlockInfo->EntryLoc,
2308 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002309 }
2310 }
2311
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +00002312 // Skip rest of block if it's not reachable.
2313 if (!CurrBlockInfo->Reachable)
2314 continue;
2315
Richard Smithaacde712012-02-03 03:30:07 +00002316 // Process continue and break blocks. Assume that the lockset for the
2317 // resulting block is unaffected by any discrepancies in them.
2318 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2319 SpecialI < SpecialN; ++SpecialI) {
2320 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2321 int PrevBlockID = PrevBlock->getBlockID();
2322 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2323
2324 if (!LocksetInitialized) {
2325 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2326 LocksetInitialized = true;
2327 } else {
2328 // Determine whether this edge is a loop terminator for diagnostic
2329 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2330 // it might also be part of a switch. Also, a subsequent destructor
2331 // might add to the lockset, in which case the real issue might be a
2332 // double lock on the other path.
2333 const Stmt *Terminator = PrevBlock->getTerminator();
2334 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2335
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002336 FactSet PrevLockset;
2337 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2338 PrevBlock, CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002339
Richard Smithaacde712012-02-03 03:30:07 +00002340 // Do not update EntrySet.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002341 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2342 PrevBlockInfo->ExitLoc,
Richard Smithaacde712012-02-03 03:30:07 +00002343 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002344 : LEK_LockedSomePredecessors,
2345 false);
Richard Smithaacde712012-02-03 03:30:07 +00002346 }
2347 }
2348
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002349 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2350
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002351 // Visit all the statements in the basic block.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002352 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2353 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002354 switch (BI->getKind()) {
2355 case CFGElement::Statement: {
2356 const CFGStmt *CS = cast<CFGStmt>(&*BI);
2357 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
2358 break;
2359 }
2360 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2361 case CFGElement::AutomaticObjectDtor: {
2362 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
2363 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
2364 AD->getDestructorDecl(AC.getASTContext()));
2365 if (!DD->hasAttrs())
2366 break;
2367
2368 // Create a dummy expression,
2369 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
John McCallf4b88a42012-03-10 09:33:50 +00002370 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002371 AD->getTriggerStmt()->getLocEnd());
2372 LocksetBuilder.handleCall(&DRE, DD);
2373 break;
2374 }
2375 default:
2376 break;
2377 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002378 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002379 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002380
2381 // For every back edge from CurrBlock (the end of the loop) to another block
2382 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2383 // the one held at the beginning of FirstLoopBlock. We can look up the
2384 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2385 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2386 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2387
2388 // if CurrBlock -> *SI is *not* a back edge
2389 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2390 continue;
2391
2392 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002393 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2394 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2395 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2396 PreLoop->EntryLoc,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002397 LEK_LockedSomeLoopIterations,
2398 false);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002399 }
2400 }
2401
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002402 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2403 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00002404
DeLesley Hutchinsd2f38822012-09-21 17:57:00 +00002405 // Skip the final check if the exit block is unreachable.
2406 if (!Final->Reachable)
2407 return;
2408
Caitlin Sadowski1748b122011-09-16 00:35:54 +00002409 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002410 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
2411 Final->ExitLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002412 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002413 LEK_NotLockedAtEndOfFunction,
2414 false);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002415}
2416
2417} // end anonymous namespace
2418
2419
2420namespace clang {
2421namespace thread_safety {
2422
2423/// \brief Check a function's CFG for thread-safety violations.
2424///
2425/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2426/// at the end of each block, and issue warnings for thread safety violations.
2427/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002428void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002429 ThreadSafetyHandler &Handler) {
2430 ThreadSafetyAnalyzer Analyzer(Handler);
2431 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002432}
2433
2434/// \brief Helper function that returns a LockKind required for the given level
2435/// of access.
2436LockKind getLockKindFromAccessKind(AccessKind AK) {
2437 switch (AK) {
2438 case AK_Read :
2439 return LK_Shared;
2440 case AK_Written :
2441 return LK_Exclusive;
2442 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00002443 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002444}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002445
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002446}} // end namespace clang::thread_safety