blob: d19e04d630d8db040abc97f94ab21e86f0c9034c [file] [log] [blame]
Caitlin Sadowski33208342011-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//
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000013// See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
Aaron Ballmanfcd5b7e2013-06-26 19:17:19 +000014// for more information.
Caitlin Sadowski33208342011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Analysis/Analyses/PostOrderCFGView.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000024#include "clang/Analysis/Analyses/ThreadSafety.h"
Aaron Ballman7c192b42014-05-09 18:26:23 +000025#include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000026#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
DeLesley Hutchins7e615c22014-04-09 22:39:43 +000027#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000028#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/AnalysisContext.h"
30#include "clang/Analysis/CFG.h"
31#include "clang/Analysis/CFGStmtMap.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000032#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000033#include "clang/Basic/SourceLocation.h"
34#include "clang/Basic/SourceManager.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000035#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/ImmutableMap.h"
38#include "llvm/ADT/PostOrderIterator.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringRef.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000041#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000042#include <algorithm>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000043#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000044#include <vector>
45
46using namespace clang;
47using namespace thread_safety;
48
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000049// Key method definition
50ThreadSafetyHandler::~ThreadSafetyHandler() {}
51
Caitlin Sadowski33208342011-09-09 16:11:56 +000052namespace {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +000053
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000054/// SExpr implements a simple expression language that is used to store,
55/// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
56/// does not capture surface syntax, and it does not distinguish between
57/// C++ concepts, like pointers and references, that have no real semantic
58/// differences. This simplicity allows SExprs to be meaningfully compared,
59/// e.g.
60/// (x) = x
61/// (*this).foo = this->foo
62/// *&a = a
Caitlin Sadowski33208342011-09-09 16:11:56 +000063///
64/// Thread-safety analysis works by comparing lock expressions. Within the
65/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
66/// a particular mutex object at run-time. Subsequent occurrences of the same
67/// expression (where "same" means syntactic equality) will refer to the same
68/// run-time object if three conditions hold:
69/// (1) Local variables in the expression, such as "x" have not changed.
70/// (2) Values on the heap that affect the expression have not changed.
71/// (3) The expression involves only pure function calls.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +000072///
Caitlin Sadowski33208342011-09-09 16:11:56 +000073/// The current implementation assumes, but does not verify, that multiple uses
74/// of the same lock expression satisfies these criteria.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000075class SExpr {
76private:
77 enum ExprOp {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +000078 EOP_Nop, ///< No-op
79 EOP_Wildcard, ///< Matches anything.
80 EOP_Universal, ///< Universal lock.
81 EOP_This, ///< This keyword.
82 EOP_NVar, ///< Named variable.
83 EOP_LVar, ///< Local variable.
84 EOP_Dot, ///< Field access
85 EOP_Call, ///< Function call
86 EOP_MCall, ///< Method call
87 EOP_Index, ///< Array index
88 EOP_Unary, ///< Unary operation
89 EOP_Binary, ///< Binary operation
90 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000091 };
92
93
94 class SExprNode {
95 private:
Ted Kremenek78094ca2012-08-22 23:50:41 +000096 unsigned char Op; ///< Opcode of the root node
97 unsigned char Flags; ///< Additional opcode-specific data
98 unsigned short Sz; ///< Number of child nodes
99 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000100
101 public:
102 SExprNode(ExprOp O, unsigned F, const void* D)
103 : Op(static_cast<unsigned char>(O)),
104 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
105 { }
106
107 unsigned size() const { return Sz; }
108 void setSize(unsigned S) { Sz = S; }
109
110 ExprOp kind() const { return static_cast<ExprOp>(Op); }
111
112 const NamedDecl* getNamedDecl() const {
113 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
114 return reinterpret_cast<const NamedDecl*>(Data);
115 }
116
117 const NamedDecl* getFunctionDecl() const {
118 assert(Op == EOP_Call || Op == EOP_MCall);
119 return reinterpret_cast<const NamedDecl*>(Data);
120 }
121
122 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
123 void setArrow(bool A) { Flags = A ? 1 : 0; }
124
125 unsigned arity() const {
126 switch (Op) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000127 case EOP_Nop: return 0;
128 case EOP_Wildcard: return 0;
129 case EOP_Universal: return 0;
130 case EOP_NVar: return 0;
131 case EOP_LVar: return 0;
132 case EOP_This: return 0;
133 case EOP_Dot: return 1;
134 case EOP_Call: return Flags+1; // First arg is function.
135 case EOP_MCall: return Flags+1; // First arg is implicit obj.
136 case EOP_Index: return 2;
137 case EOP_Unary: return 1;
138 case EOP_Binary: return 2;
139 case EOP_Unknown: return Flags;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000140 }
141 return 0;
142 }
143
144 bool operator==(const SExprNode& Other) const {
145 // Ignore flags and size -- they don't matter.
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000146 return (Op == Other.Op &&
147 Data == Other.Data);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000148 }
149
150 bool operator!=(const SExprNode& Other) const {
151 return !(*this == Other);
152 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000153
154 bool matches(const SExprNode& Other) const {
155 return (*this == Other) ||
156 (Op == EOP_Wildcard) ||
157 (Other.Op == EOP_Wildcard);
158 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000159 };
160
Caitlin Sadowski33208342011-09-09 16:11:56 +0000161
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000162 /// \brief Encapsulates the lexical context of a function call. The lexical
163 /// context includes the arguments to the call, including the implicit object
164 /// argument. When an attribute containing a mutex expression is attached to
165 /// a method, the expression may refer to formal parameters of the method.
166 /// Actual arguments must be substituted for formal parameters to derive
167 /// the appropriate mutex expression in the lexical context where the function
168 /// is called. PrevCtx holds the context in which the arguments themselves
169 /// should be evaluated; multiple calling contexts can be chained together
170 /// by the lock_returned attribute.
171 struct CallingContext {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000172 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
173 const Expr* SelfArg; // Implicit object argument -- e.g. 'this'
174 bool SelfArrow; // is Self referred to with -> or .?
175 unsigned NumArgs; // Number of funArgs
176 const Expr* const* FunArgs; // Function arguments
177 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000178
Aaron Ballman69bb5922014-03-06 19:37:24 +0000179 CallingContext(const NamedDecl *D)
180 : AttrDecl(D), SelfArg(0), SelfArrow(false), NumArgs(0), FunArgs(0),
181 PrevCtx(0) {}
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000182 };
183
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000184 typedef SmallVector<SExprNode, 4> NodeVector;
185
186private:
187 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
188 // the list to be traversed as a tree.
189 NodeVector NodeVec;
190
191private:
Aaron Ballman19842c42014-03-06 19:25:11 +0000192 unsigned make(ExprOp O, unsigned F = 0, const void *D = 0) {
193 NodeVec.push_back(SExprNode(O, F, D));
194 return NodeVec.size() - 1;
195 }
196
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000197 unsigned makeNop() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000198 return make(EOP_Nop);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000199 }
200
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000201 unsigned makeWildcard() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000202 return make(EOP_Wildcard);
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000203 }
204
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000205 unsigned makeUniversal() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000206 return make(EOP_Universal);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000207 }
208
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000209 unsigned makeNamedVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000210 return make(EOP_NVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000211 }
212
213 unsigned makeLocalVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000214 return make(EOP_LVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000215 }
216
217 unsigned makeThis() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000218 return make(EOP_This);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000219 }
220
221 unsigned makeDot(const NamedDecl *D, bool Arrow) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000222 return make(EOP_Dot, Arrow ? 1 : 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000223 }
224
225 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000226 return make(EOP_Call, NumArgs, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000227 }
228
DeLesley Hutchinsb78aeed2012-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) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000243 return make(EOP_MCall, NumArgs, getFirstVirtualDecl(D));
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000244 }
245
246 unsigned makeIndex() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000247 return make(EOP_Index);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000248 }
249
250 unsigned makeUnary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000251 return make(EOP_Unary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000252 }
253
254 unsigned makeBinary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000255 return make(EOP_Binary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000256 }
257
258 unsigned makeUnknown(unsigned Arity) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000259 return make(EOP_Unknown, Arity);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000260 }
261
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000262 inline bool isCalleeArrow(const Expr *E) {
263 const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
264 return ME ? ME->isArrow() : false;
265 }
266
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000267 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000268 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000269 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000270 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000271 ///
272 /// NDeref returns the number of Derefence and AddressOf operations
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000273 /// preceding the Expr; this is used to decide whether to pretty-print
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000274 /// SExprs with . or ->.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000275 unsigned buildSExpr(const Expr *Exp, CallingContext* CallCtx,
276 int* NDeref = 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000277 if (!Exp)
278 return 0;
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000279
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000280 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
281 const NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
282 const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000283 if (PV) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000284 const FunctionDecl *FD =
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000285 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
286 unsigned i = PV->getFunctionScopeIndex();
287
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000288 if (CallCtx && CallCtx->FunArgs &&
289 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000290 // Substitute call arguments for references to function parameters
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000291 assert(i < CallCtx->NumArgs);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000292 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000293 }
294 // Map the param back to the param of the original function declaration.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000295 makeNamedVar(FD->getParamDecl(i));
296 return 1;
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000297 }
298 // Not a function parameter -- just store the reference.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000299 makeNamedVar(ND);
300 return 1;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000301 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000302 // Substitute parent for 'this'
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000303 if (CallCtx && CallCtx->SelfArg) {
304 if (!CallCtx->SelfArrow && NDeref)
305 // 'this' is a pointer, but self is not, so need to take address.
306 --(*NDeref);
307 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
308 }
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000309 else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000310 makeThis();
311 return 1;
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000312 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000313 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
314 const NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000315 int ImplicitDeref = ME->isArrow() ? 1 : 0;
316 unsigned Root = makeDot(ND, false);
317 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
318 NodeVec[Root].setArrow(ImplicitDeref > 0);
319 NodeVec[Root].setSize(Sz + 1);
320 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000321 } else if (const CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000322 // When calling a function with a lock_returned attribute, replace
323 // the function call with the expression in lock_returned.
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000324 const CXXMethodDecl *MD = CMCE->getMethodDecl()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000325 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000326 CallingContext LRCallCtx(CMCE->getMethodDecl());
327 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000328 LRCallCtx.SelfArrow = isCalleeArrow(CMCE->getCallee());
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000329 LRCallCtx.NumArgs = CMCE->getNumArgs();
330 LRCallCtx.FunArgs = CMCE->getArgs();
331 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000332 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000333 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000334 // Hack to treat smart pointers and iterators as pointers;
335 // ignore any method named get().
336 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
337 CMCE->getNumArgs() == 0) {
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000338 if (NDeref && isCalleeArrow(CMCE->getCallee()))
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000339 ++(*NDeref);
340 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000341 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000342 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000343 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000344 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000345 const Expr* const* CallArgs = CMCE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000346 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000347 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000348 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000349 NodeVec[Root].setSize(Sz + 1);
350 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000351 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000352 const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000353 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000354 CallingContext LRCallCtx(CE->getDirectCallee());
355 LRCallCtx.NumArgs = CE->getNumArgs();
356 LRCallCtx.FunArgs = CE->getArgs();
357 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000358 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000359 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000360 // Treat smart pointers and iterators as pointers;
361 // ignore the * and -> operators.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000362 if (const CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000363 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000364 if (k == OO_Star) {
365 if (NDeref) ++(*NDeref);
366 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
367 }
368 else if (k == OO_Arrow) {
369 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000370 }
371 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000372 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000373 unsigned Root = makeCall(NumCallArgs, 0);
374 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000375 const Expr* const* CallArgs = CE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000376 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000377 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000378 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000379 NodeVec[Root].setSize(Sz+1);
380 return Sz+1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000381 } else if (const BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000382 unsigned Root = makeBinary();
383 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
384 Sz += buildSExpr(BOE->getRHS(), CallCtx);
385 NodeVec[Root].setSize(Sz);
386 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000387 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000388 // Ignore & and * operators -- they're no-ops.
389 // However, we try to figure out whether the expression is a pointer,
390 // so we can use . and -> appropriately in error messages.
391 if (UOE->getOpcode() == UO_Deref) {
392 if (NDeref) ++(*NDeref);
393 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
394 }
395 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000396 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
397 if (DRE->getDecl()->isCXXInstanceMember()) {
398 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
399 // We interpret this syntax specially, as a wildcard.
400 unsigned Root = makeDot(DRE->getDecl(), false);
401 makeWildcard();
402 NodeVec[Root].setSize(2);
403 return 2;
404 }
405 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000406 if (NDeref) --(*NDeref);
407 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
408 }
409 unsigned Root = makeUnary();
410 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
411 NodeVec[Root].setSize(Sz);
412 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000413 } else if (const ArraySubscriptExpr *ASE =
414 dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000415 unsigned Root = makeIndex();
416 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
417 Sz += buildSExpr(ASE->getIdx(), CallCtx);
418 NodeVec[Root].setSize(Sz);
419 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000420 } else if (const AbstractConditionalOperator *CE =
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000421 dyn_cast<AbstractConditionalOperator>(Exp)) {
422 unsigned Root = makeUnknown(3);
423 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
424 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
425 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
426 NodeVec[Root].setSize(Sz);
427 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000428 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000429 unsigned Root = makeUnknown(3);
430 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
431 Sz += buildSExpr(CE->getLHS(), CallCtx);
432 Sz += buildSExpr(CE->getRHS(), CallCtx);
433 NodeVec[Root].setSize(Sz);
434 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000435 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000436 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000437 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000438 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000439 } else if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000440 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000441 } else if (const CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000442 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000443 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins0c1da202012-07-03 18:25:56 +0000444 isa<CXXNullPtrLiteralExpr>(Exp) ||
445 isa<GNUNullExpr>(Exp) ||
446 isa<CXXBoolLiteralExpr>(Exp) ||
447 isa<FloatingLiteral>(Exp) ||
448 isa<ImaginaryLiteral>(Exp) ||
449 isa<IntegerLiteral>(Exp) ||
450 isa<StringLiteral>(Exp) ||
451 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000452 makeNop();
453 return 1; // FIXME: Ignore literals for now
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000454 } else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000455 makeNop();
456 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000457 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000458 }
459
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000460 /// \brief Construct a SExpr from an expression.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000461 /// \param MutexExp The original mutex expression within an attribute
462 /// \param DeclExp An expression involving the Decl on which the attribute
463 /// occurs.
464 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000465 void buildSExprFromExpr(const Expr *MutexExp, const Expr *DeclExp,
466 const NamedDecl *D, VarDecl *SelfDecl = 0) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000467 CallingContext CallCtx(D);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000468
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000469 if (MutexExp) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000470 if (const StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000471 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 Hutchins3c3d57b2012-08-31 21:57:32 +0000480 }
481
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000482 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000483 if (DeclExp == 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000484 buildSExpr(MutexExp, 0);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000485 return;
486 }
487
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000488 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000489 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000490 if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000491 CallCtx.SelfArg = ME->getBase();
492 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000493 } else if (const CXXMemberCallExpr *CE =
494 dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000495 CallCtx.SelfArg = CE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000496 CallCtx.SelfArrow = isCalleeArrow(CE->getCallee());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000497 CallCtx.NumArgs = CE->getNumArgs();
498 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000499 } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000500 CallCtx.NumArgs = CE->getNumArgs();
501 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000502 } else if (const CXXConstructExpr *CE =
503 dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000504 CallCtx.SelfArg = 0; // Will be set below
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000505 CallCtx.NumArgs = CE->getNumArgs();
506 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +0000507 } else if (D && isa<CXXDestructorDecl>(D)) {
508 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000509 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000510 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000511
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000512 // Hack to handle constructors, where self cannot be recovered from
513 // the expression.
514 if (SelfDecl && !CallCtx.SelfArg) {
515 DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
516 SelfDecl->getLocation());
517 CallCtx.SelfArg = &SelfDRE;
518
519 // If the attribute has no arguments, then assume the argument is "this".
520 if (MutexExp == 0)
521 buildSExpr(CallCtx.SelfArg, 0);
522 else // For most attributes.
523 buildSExpr(MutexExp, &CallCtx);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000524 return;
525 }
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000526
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000527 // If the attribute has no arguments, then assume the argument is "this".
528 if (MutexExp == 0)
529 buildSExpr(CallCtx.SelfArg, 0);
530 else // For most attributes.
531 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski33208342011-09-09 16:11:56 +0000532 }
533
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000534 /// \brief Get index of next sibling of node i.
535 unsigned getNextSibling(unsigned i) const {
536 return i + NodeVec[i].size();
537 }
538
Caitlin Sadowski33208342011-09-09 16:11:56 +0000539public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000540 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000541
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000542 /// \param MutexExp The original mutex expression within an attribute
543 /// \param DeclExp An expression involving the Decl on which the attribute
544 /// occurs.
545 /// \param D The declaration to which the lock/unlock attribute is attached.
546 /// Caller must check isValid() after construction.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000547 SExpr(const Expr* MutexExp, const Expr *DeclExp, const NamedDecl* D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000548 VarDecl *SelfDecl=0) {
549 buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl);
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000550 }
551
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000552 /// Return true if this is a valid decl sequence.
553 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000554 bool isValid() const {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000555 return !NodeVec.empty();
Caitlin Sadowski33208342011-09-09 16:11:56 +0000556 }
557
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000558 bool shouldIgnore() const {
559 // Nop is a mutex that we have decided to deliberately ignore.
560 assert(NodeVec.size() > 0 && "Invalid Mutex");
561 return NodeVec[0].kind() == EOP_Nop;
562 }
563
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000564 bool isUniversal() const {
565 assert(NodeVec.size() > 0 && "Invalid Mutex");
566 return NodeVec[0].kind() == EOP_Universal;
567 }
568
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000569 /// Issue a warning about an invalid lock expression
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000570 static void warnInvalidLock(ThreadSafetyHandler &Handler,
Aaron Ballmane0449042014-04-01 21:43:23 +0000571 const Expr *MutexExp, const Expr *DeclExp,
572 const NamedDecl *D, StringRef Kind) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000573 SourceLocation Loc;
574 if (DeclExp)
575 Loc = DeclExp->getExprLoc();
576
577 // FIXME: add a note about the attribute location in MutexExp or D
578 if (Loc.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +0000579 Handler.handleInvalidLockExp(Kind, Loc);
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000580 }
581
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000582 bool operator==(const SExpr &other) const {
583 return NodeVec == other.NodeVec;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000584 }
585
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000586 bool operator!=(const SExpr &other) const {
Caitlin Sadowski33208342011-09-09 16:11:56 +0000587 return !(*this == other);
588 }
589
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000590 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
591 if (NodeVec[i].matches(Other.NodeVec[j])) {
DeLesley Hutchins138568b2012-09-11 23:04:49 +0000592 unsigned ni = NodeVec[i].arity();
593 unsigned nj = Other.NodeVec[j].arity();
594 unsigned n = (ni < nj) ? ni : nj;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000595 bool Result = true;
596 unsigned ci = i+1; // first child of i
597 unsigned cj = j+1; // first child of j
598 for (unsigned k = 0; k < n;
599 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
600 Result = Result && matches(Other, ci, cj);
601 }
602 return Result;
603 }
604 return false;
605 }
606
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000607 // A partial match between a.mu and b.mu returns true a and b have the same
608 // type (and thus mu refers to the same mutex declaration), regardless of
609 // whether a and b are different objects or not.
610 bool partiallyMatches(const SExpr &Other) const {
611 if (NodeVec[0].kind() == EOP_Dot)
612 return NodeVec[0].matches(Other.NodeVec[0]);
613 return false;
614 }
615
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000616 /// \brief Pretty print a lock expression for use in error messages.
617 std::string toString(unsigned i = 0) const {
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000618 assert(isValid());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000619 if (i >= NodeVec.size())
620 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000621
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000622 const SExprNode* N = &NodeVec[i];
623 switch (N->kind()) {
624 case EOP_Nop:
625 return "_";
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000626 case EOP_Wildcard:
627 return "(?)";
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000628 case EOP_Universal:
629 return "*";
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000630 case EOP_This:
631 return "this";
632 case EOP_NVar:
633 case EOP_LVar: {
634 return N->getNamedDecl()->getNameAsString();
635 }
636 case EOP_Dot: {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000637 if (NodeVec[i+1].kind() == EOP_Wildcard) {
638 std::string S = "&";
639 S += N->getNamedDecl()->getQualifiedNameAsString();
640 return S;
641 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000642 std::string FieldName = N->getNamedDecl()->getNameAsString();
643 if (NodeVec[i+1].kind() == EOP_This)
644 return FieldName;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000645
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000646 std::string S = toString(i+1);
647 if (N->isArrow())
648 return S + "->" + FieldName;
649 else
650 return S + "." + FieldName;
651 }
652 case EOP_Call: {
653 std::string S = toString(i+1) + "(";
654 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000655 unsigned ci = getNextSibling(i+1);
656 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000657 S += toString(ci);
658 if (k+1 < NumArgs) S += ",";
659 }
660 S += ")";
661 return S;
662 }
663 case EOP_MCall: {
664 std::string S = "";
665 if (NodeVec[i+1].kind() != EOP_This)
666 S = toString(i+1) + ".";
667 if (const NamedDecl *D = N->getFunctionDecl())
668 S += D->getNameAsString() + "(";
669 else
670 S += "#(";
671 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000672 unsigned ci = getNextSibling(i+1);
673 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000674 S += toString(ci);
675 if (k+1 < NumArgs) S += ",";
676 }
677 S += ")";
678 return S;
679 }
680 case EOP_Index: {
681 std::string S1 = toString(i+1);
682 std::string S2 = toString(i+1 + NodeVec[i+1].size());
683 return S1 + "[" + S2 + "]";
684 }
685 case EOP_Unary: {
686 std::string S = toString(i+1);
687 return "#" + S;
688 }
689 case EOP_Binary: {
690 std::string S1 = toString(i+1);
691 std::string S2 = toString(i+1 + NodeVec[i+1].size());
692 return "(" + S1 + "#" + S2 + ")";
693 }
694 case EOP_Unknown: {
695 unsigned NumChildren = N->arity();
696 if (NumChildren == 0)
697 return "(...)";
698 std::string S = "(";
699 unsigned ci = i+1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000700 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000701 S += toString(ci);
702 if (j+1 < NumChildren) S += "#";
703 }
704 S += ")";
705 return S;
706 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000707 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000708 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000709 }
710};
711
Aaron Ballman7c192b42014-05-09 18:26:23 +0000712/// \brief Attempts to create an LExpr from a Clang Expr. If an LExpr cannot be
713/// constructed, returns a null pointer. Recursive function that terminates when
714/// the complete expression is handled, or when a failure to create an LExpr
715/// occurs.
716static clang::threadSafety::lexpr::LExpr *
717buildLExpr(threadSafety::til::MemRegionRef &Arena, const Expr *CurExpr) {
718 using namespace clang::threadSafety::lexpr;
719 using namespace clang::threadSafety::til;
720
721 if (const auto *DRE = dyn_cast<DeclRefExpr>(CurExpr)) {
722 // TODO: Construct the til::SExpr leaf properly.
723 return new Terminal(new (Arena) Variable());
724 } else if (const auto *ME = dyn_cast<MemberExpr>(CurExpr)) {
725 // TODO: Construct the til::SExpr leaf properly.
726 return new Terminal(new (Arena) Variable());
727 } else if (const auto *BOE = dyn_cast<BinaryOperator>(CurExpr)) {
728 switch (BOE->getOpcode()) {
729 case BO_LOr:
730 case BO_LAnd: {
731 auto *LHS = buildLExpr(Arena, BOE->getLHS());
732 auto *RHS = buildLExpr(Arena, BOE->getRHS());
733 if (!LHS || !RHS)
734 return nullptr;
735
736 if (BOE->getOpcode() == BO_LOr)
737 return new Or(LHS, RHS);
738 else
739 return new And(LHS, RHS);
740 }
741 default:
742 break;
743 }
744 } else if (const auto *UOE = dyn_cast<UnaryOperator>(CurExpr)) {
745 if (UOE->getOpcode() == UO_LNot) {
746 auto *E = buildLExpr(Arena, UOE->getSubExpr());
747 return new Not(E);
748 }
749 } else if (const auto *CE = dyn_cast<CastExpr>(CurExpr)) {
750 return buildLExpr(Arena, CE->getSubExpr());
751 } else if (const auto *PE = dyn_cast<ParenExpr>(CurExpr)) {
752 return buildLExpr(Arena, PE->getSubExpr());
753 }
754
755 return nullptr;
756}
757
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000758/// \brief A short list of SExprs
759class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000760public:
Aaron Ballmancea26092014-03-06 19:10:16 +0000761 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000762 void push_back_nodup(const SExpr& M) {
Aaron Ballmancea26092014-03-06 19:10:16 +0000763 if (end() == std::find(begin(), end(), M))
764 push_back(M);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000765 }
766};
767
Caitlin Sadowski33208342011-09-09 16:11:56 +0000768/// \brief This is a helper class that stores info about the most recent
769/// accquire of a Lock.
770///
771/// The main body of the analysis maps MutexIDs to LockDatas.
772struct LockData {
773 SourceLocation AcquireLoc;
774
775 /// \brief LKind stores whether a lock is held shared or exclusively.
776 /// Note that this analysis does not currently support either re-entrant
777 /// locking or lock "upgrading" and "downgrading" between exclusive and
778 /// shared.
779 ///
780 /// FIXME: add support for re-entrant locking and lock up/downgrading
781 LockKind LKind;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000782 bool Asserted; // for asserted locks
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000783 bool Managed; // for ScopedLockable objects
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000784 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski33208342011-09-09 16:11:56 +0000785
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000786 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M=false,
787 bool Asrt=false)
788 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(Asrt), Managed(M),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000789 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000790 {}
791
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000792 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000793 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(false), Managed(false),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000794 UnderlyingMutex(Mu)
795 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000796
797 bool operator==(const LockData &other) const {
798 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
799 }
800
801 bool operator!=(const LockData &other) const {
802 return !(*this == other);
803 }
804
805 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000806 ID.AddInteger(AcquireLoc.getRawEncoding());
807 ID.AddInteger(LKind);
808 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000809
810 bool isAtLeast(LockKind LK) {
811 return (LK == LK_Shared) || (LKind == LK_Exclusive);
812 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000813};
814
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000815
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000816/// \brief A FactEntry stores a single fact that is known at a particular point
817/// in the program execution. Currently, this is information regarding a lock
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000818/// that is held at that point.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000819struct FactEntry {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000820 SExpr MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000821 LockData LDat;
822
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000823 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000824 : MutID(M), LDat(L)
825 { }
826};
827
828
829typedef unsigned short FactID;
830
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000831/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000832/// the analysis of a single routine.
833class FactManager {
834private:
835 std::vector<FactEntry> Facts;
836
837public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000838 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000839 Facts.push_back(FactEntry(M,L));
840 return static_cast<unsigned short>(Facts.size() - 1);
841 }
842
843 const FactEntry& operator[](FactID F) const { return Facts[F]; }
844 FactEntry& operator[](FactID F) { return Facts[F]; }
845};
846
847
848/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000849/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000850/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000851/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000852/// locks, so we can get away with doing a linear search for lookup. Note
853/// that a hashtable or map is inappropriate in this case, because lookups
854/// may involve partial pattern matches, rather than exact matches.
855class FactSet {
856private:
857 typedef SmallVector<FactID, 4> FactVec;
858
859 FactVec FactIDs;
860
861public:
862 typedef FactVec::iterator iterator;
863 typedef FactVec::const_iterator const_iterator;
864
865 iterator begin() { return FactIDs.begin(); }
866 const_iterator begin() const { return FactIDs.begin(); }
867
868 iterator end() { return FactIDs.end(); }
869 const_iterator end() const { return FactIDs.end(); }
870
871 bool isEmpty() const { return FactIDs.size() == 0; }
872
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000873 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000874 FactID F = FM.newLock(M, L);
875 FactIDs.push_back(F);
876 return F;
877 }
878
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000879 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000880 unsigned n = FactIDs.size();
881 if (n == 0)
882 return false;
883
884 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000885 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000886 FactIDs[i] = FactIDs[n-1];
887 FactIDs.pop_back();
888 return true;
889 }
890 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000891 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000892 FactIDs.pop_back();
893 return true;
894 }
895 return false;
896 }
897
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000898 // Returns an iterator
899 iterator findLockIter(FactManager &FM, const SExpr &M) {
900 for (iterator I = begin(), E = end(); I != E; ++I) {
901 const SExpr &Exp = FM[*I].MutID;
902 if (Exp.matches(M))
903 return I;
904 }
905 return end();
906 }
907
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000908 LockData* findLock(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000909 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000910 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000911 if (Exp.matches(M))
912 return &FM[*I].LDat;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000913 }
914 return 0;
915 }
916
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000917 LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000918 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000919 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000920 if (Exp.matches(M) || Exp.isUniversal())
921 return &FM[*I].LDat;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000922 }
923 return 0;
924 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000925
926 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
927 for (const_iterator I=begin(), E=end(); I != E; ++I) {
928 const SExpr& Exp = FM[*I].MutID;
929 if (Exp.partiallyMatches(M)) return &FM[*I];
930 }
931 return 0;
932 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000933};
934
935
936
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000937/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski33208342011-09-09 16:11:56 +0000938/// been locked.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000939typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000940typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000941
942class LocalVariableMap;
943
Richard Smith92286672012-02-03 04:45:26 +0000944/// A side (entry or exit) of a CFG node.
945enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000946
947/// CFGBlockInfo is a struct which contains all the information that is
948/// maintained for each block in the CFG. See LocalVariableMap for more
949/// information about the contexts.
950struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000951 FactSet EntrySet; // Lockset held at entry to block
952 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000953 LocalVarContext EntryContext; // Context held at entry to block
954 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000955 SourceLocation EntryLoc; // Location of first statement in block
956 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000957 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000958 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000959
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000960 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000961 return Side == CBS_Entry ? EntrySet : ExitSet;
962 }
963 SourceLocation getLocation(CFGBlockSide Side) const {
964 return Side == CBS_Entry ? EntryLoc : ExitLoc;
965 }
966
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000967private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000968 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000969 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000970 { }
971
972public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000973 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000974};
975
976
977
978// A LocalVariableMap maintains a map from local variables to their currently
979// valid definitions. It provides SSA-like functionality when traversing the
980// CFG. Like SSA, each definition or assignment to a variable is assigned a
981// unique name (an integer), which acts as the SSA name for that definition.
982// The total set of names is shared among all CFG basic blocks.
983// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
984// with their SSA-names. Instead, we compute a Context for each point in the
985// code, which maps local variables to the appropriate SSA-name. This map
986// changes with each assignment.
987//
988// The map is computed in a single pass over the CFG. Subsequent analyses can
989// then query the map to find the appropriate Context for a statement, and use
990// that Context to look up the definitions of variables.
991class LocalVariableMap {
992public:
993 typedef LocalVarContext Context;
994
995 /// A VarDefinition consists of an expression, representing the value of the
996 /// variable, along with the context in which that expression should be
997 /// interpreted. A reference VarDefinition does not itself contain this
998 /// information, but instead contains a pointer to a previous VarDefinition.
999 struct VarDefinition {
1000 public:
1001 friend class LocalVariableMap;
1002
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001003 const NamedDecl *Dec; // The original declaration for this variable.
1004 const Expr *Exp; // The expression for this variable, OR
1005 unsigned Ref; // Reference to another VarDefinition
1006 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001007
1008 bool isReference() { return !Exp; }
1009
1010 private:
1011 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001012 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001013 : Dec(D), Exp(E), Ref(0), Ctx(C)
1014 { }
1015
1016 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001017 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001018 : Dec(D), Exp(0), Ref(R), Ctx(C)
1019 { }
1020 };
1021
1022private:
1023 Context::Factory ContextFactory;
1024 std::vector<VarDefinition> VarDefinitions;
1025 std::vector<unsigned> CtxIndices;
1026 std::vector<std::pair<Stmt*, Context> > SavedContexts;
1027
1028public:
1029 LocalVariableMap() {
1030 // index 0 is a placeholder for undefined variables (aka phi-nodes).
1031 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
1032 }
1033
1034 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001035 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001036 const unsigned *i = Ctx.lookup(D);
1037 if (!i)
1038 return 0;
1039 assert(*i < VarDefinitions.size());
1040 return &VarDefinitions[*i];
1041 }
1042
1043 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001044 /// NULL if the expression is not statically known. If successful, also
1045 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001046 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001047 const unsigned *P = Ctx.lookup(D);
1048 if (!P)
1049 return 0;
1050
1051 unsigned i = *P;
1052 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001053 if (VarDefinitions[i].Exp) {
1054 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001055 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001056 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001057 i = VarDefinitions[i].Ref;
1058 }
1059 return 0;
1060 }
1061
1062 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
1063
1064 /// Return the next context after processing S. This function is used by
1065 /// clients of the class to get the appropriate context when traversing the
1066 /// CFG. It must be called for every assignment or DeclStmt.
1067 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1068 if (SavedContexts[CtxIndex+1].first == S) {
1069 CtxIndex++;
1070 Context Result = SavedContexts[CtxIndex].second;
1071 return Result;
1072 }
1073 return C;
1074 }
1075
1076 void dumpVarDefinitionName(unsigned i) {
1077 if (i == 0) {
1078 llvm::errs() << "Undefined";
1079 return;
1080 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001081 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001082 if (!Dec) {
1083 llvm::errs() << "<<NULL>>";
1084 return;
1085 }
1086 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +00001087 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001088 }
1089
1090 /// Dumps an ASCII representation of the variable map to llvm::errs()
1091 void dump() {
1092 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001093 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001094 unsigned Ref = VarDefinitions[i].Ref;
1095
1096 dumpVarDefinitionName(i);
1097 llvm::errs() << " = ";
1098 if (Exp) Exp->dump();
1099 else {
1100 dumpVarDefinitionName(Ref);
1101 llvm::errs() << "\n";
1102 }
1103 }
1104 }
1105
1106 /// Dumps an ASCII representation of a Context to llvm::errs()
1107 void dumpContext(Context C) {
1108 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001109 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001110 D->printName(llvm::errs());
1111 const unsigned *i = C.lookup(D);
1112 llvm::errs() << " -> ";
1113 dumpVarDefinitionName(*i);
1114 llvm::errs() << "\n";
1115 }
1116 }
1117
1118 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001119 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
1120 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001121
1122protected:
1123 // Get the current context index
1124 unsigned getContextIndex() { return SavedContexts.size()-1; }
1125
1126 // Save the current context for later replay
1127 void saveContext(Stmt *S, Context C) {
1128 SavedContexts.push_back(std::make_pair(S,C));
1129 }
1130
1131 // Adds a new definition to the given context, and returns a new context.
1132 // This method should be called when declaring a new variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001133 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001134 assert(!Ctx.contains(D));
1135 unsigned newID = VarDefinitions.size();
1136 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1137 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1138 return NewCtx;
1139 }
1140
1141 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001142 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001143 unsigned newID = VarDefinitions.size();
1144 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1145 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1146 return NewCtx;
1147 }
1148
1149 // Updates a definition only if that definition is already in the map.
1150 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001151 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001152 if (Ctx.contains(D)) {
1153 unsigned newID = VarDefinitions.size();
1154 Context NewCtx = ContextFactory.remove(Ctx, D);
1155 NewCtx = ContextFactory.add(NewCtx, D, newID);
1156 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1157 return NewCtx;
1158 }
1159 return Ctx;
1160 }
1161
1162 // Removes a definition from the context, but keeps the variable name
1163 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001164 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001165 Context NewCtx = Ctx;
1166 if (NewCtx.contains(D)) {
1167 NewCtx = ContextFactory.remove(NewCtx, D);
1168 NewCtx = ContextFactory.add(NewCtx, D, 0);
1169 }
1170 return NewCtx;
1171 }
1172
1173 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001174 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001175 Context NewCtx = Ctx;
1176 if (NewCtx.contains(D)) {
1177 NewCtx = ContextFactory.remove(NewCtx, D);
1178 }
1179 return NewCtx;
1180 }
1181
1182 Context intersectContexts(Context C1, Context C2);
1183 Context createReferenceContext(Context C);
1184 void intersectBackEdge(Context C1, Context C2);
1185
1186 friend class VarMapBuilder;
1187};
1188
1189
1190// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001191CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1192 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001193}
1194
1195
1196/// Visitor which builds a LocalVariableMap
1197class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1198public:
1199 LocalVariableMap* VMap;
1200 LocalVariableMap::Context Ctx;
1201
1202 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1203 : VMap(VM), Ctx(C) {}
1204
1205 void VisitDeclStmt(DeclStmt *S);
1206 void VisitBinaryOperator(BinaryOperator *BO);
1207};
1208
1209
1210// Add new local variables to the variable map
1211void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1212 bool modifiedCtx = false;
1213 DeclGroupRef DGrp = S->getDeclGroup();
1214 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1215 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1216 Expr *E = VD->getInit();
1217
1218 // Add local variables with trivial type to the variable map
1219 QualType T = VD->getType();
1220 if (T.isTrivialType(VD->getASTContext())) {
1221 Ctx = VMap->addDefinition(VD, E, Ctx);
1222 modifiedCtx = true;
1223 }
1224 }
1225 }
1226 if (modifiedCtx)
1227 VMap->saveContext(S, Ctx);
1228}
1229
1230// Update local variable definitions in variable map
1231void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1232 if (!BO->isAssignmentOp())
1233 return;
1234
1235 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1236
1237 // Update the variable map and current context.
1238 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1239 ValueDecl *VDec = DRE->getDecl();
1240 if (Ctx.lookup(VDec)) {
1241 if (BO->getOpcode() == BO_Assign)
1242 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1243 else
1244 // FIXME -- handle compound assignment operators
1245 Ctx = VMap->clearDefinition(VDec, Ctx);
1246 VMap->saveContext(BO, Ctx);
1247 }
1248 }
1249}
1250
1251
1252// Computes the intersection of two contexts. The intersection is the
1253// set of variables which have the same definition in both contexts;
1254// variables with different definitions are discarded.
1255LocalVariableMap::Context
1256LocalVariableMap::intersectContexts(Context C1, Context C2) {
1257 Context Result = C1;
1258 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001259 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001260 unsigned i1 = I.getData();
1261 const unsigned *i2 = C2.lookup(Dec);
1262 if (!i2) // variable doesn't exist on second path
1263 Result = removeDefinition(Dec, Result);
1264 else if (*i2 != i1) // variable exists, but has different definition
1265 Result = clearDefinition(Dec, Result);
1266 }
1267 return Result;
1268}
1269
1270// For every variable in C, create a new variable that refers to the
1271// definition in C. Return a new context that contains these new variables.
1272// (We use this for a naive implementation of SSA on loop back-edges.)
1273LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1274 Context Result = getEmptyContext();
1275 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001276 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001277 unsigned i = I.getData();
1278 Result = addReference(Dec, i, Result);
1279 }
1280 return Result;
1281}
1282
1283// This routine also takes the intersection of C1 and C2, but it does so by
1284// altering the VarDefinitions. C1 must be the result of an earlier call to
1285// createReferenceContext.
1286void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1287 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001288 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001289 unsigned i1 = I.getData();
1290 VarDefinition *VDef = &VarDefinitions[i1];
1291 assert(VDef->isReference());
1292
1293 const unsigned *i2 = C2.lookup(Dec);
1294 if (!i2 || (*i2 != i1))
1295 VDef->Ref = 0; // Mark this variable as undefined
1296 }
1297}
1298
1299
1300// Traverse the CFG in topological order, so all predecessors of a block
1301// (excluding back-edges) are visited before the block itself. At
1302// each point in the code, we calculate a Context, which holds the set of
1303// variable definitions which are visible at that point in execution.
1304// Visible variables are mapped to their definitions using an array that
1305// contains all definitions.
1306//
1307// At join points in the CFG, the set is computed as the intersection of
1308// the incoming sets along each edge, E.g.
1309//
1310// { Context | VarDefinitions }
1311// int x = 0; { x -> x1 | x1 = 0 }
1312// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1313// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1314// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1315// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1316//
1317// This is essentially a simpler and more naive version of the standard SSA
1318// algorithm. Those definitions that remain in the intersection are from blocks
1319// that strictly dominate the current block. We do not bother to insert proper
1320// phi nodes, because they are not used in our analysis; instead, wherever
1321// a phi node would be required, we simply remove that definition from the
1322// context (E.g. x above).
1323//
1324// The initial traversal does not capture back-edges, so those need to be
1325// handled on a separate pass. Whenever the first pass encounters an
1326// incoming back edge, it duplicates the context, creating new definitions
1327// that refer back to the originals. (These correspond to places where SSA
1328// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001329// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001330// node was actually required.) E.g.
1331//
1332// { Context | VarDefinitions }
1333// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1334// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1335// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1336// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1337//
1338void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001339 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001340 std::vector<CFGBlockInfo> &BlockInfo) {
1341 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1342
1343 CtxIndices.resize(CFGraph->getNumBlockIDs());
1344
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001345 for (const auto *CurrBlock : *SortedGraph) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001346 int CurrBlockID = CurrBlock->getBlockID();
1347 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1348
1349 VisitedBlocks.insert(CurrBlock);
1350
1351 // Calculate the entry context for the current block
1352 bool HasBackEdges = false;
1353 bool CtxInit = true;
1354 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1355 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1356 // if *PI -> CurrBlock is a back edge, so skip it
1357 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1358 HasBackEdges = true;
1359 continue;
1360 }
1361
1362 int PrevBlockID = (*PI)->getBlockID();
1363 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1364
1365 if (CtxInit) {
1366 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1367 CtxInit = false;
1368 }
1369 else {
1370 CurrBlockInfo->EntryContext =
1371 intersectContexts(CurrBlockInfo->EntryContext,
1372 PrevBlockInfo->ExitContext);
1373 }
1374 }
1375
1376 // Duplicate the context if we have back-edges, so we can call
1377 // intersectBackEdges later.
1378 if (HasBackEdges)
1379 CurrBlockInfo->EntryContext =
1380 createReferenceContext(CurrBlockInfo->EntryContext);
1381
1382 // Create a starting context index for the current block
1383 saveContext(0, CurrBlockInfo->EntryContext);
1384 CurrBlockInfo->EntryIndex = getContextIndex();
1385
1386 // Visit all the statements in the basic block.
1387 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1388 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1389 BE = CurrBlock->end(); BI != BE; ++BI) {
1390 switch (BI->getKind()) {
1391 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00001392 CFGStmt CS = BI->castAs<CFGStmt>();
1393 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001394 break;
1395 }
1396 default:
1397 break;
1398 }
1399 }
1400 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1401
1402 // Mark variables on back edges as "unknown" if they've been changed.
1403 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1404 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1405 // if CurrBlock -> *SI is *not* a back edge
1406 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1407 continue;
1408
1409 CFGBlock *FirstLoopBlock = *SI;
1410 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1411 Context LoopEnd = CurrBlockInfo->ExitContext;
1412 intersectBackEdge(LoopBegin, LoopEnd);
1413 }
1414 }
1415
1416 // Put an extra entry at the end of the indexed context array
1417 unsigned exitID = CFGraph->getExit().getBlockID();
1418 saveContext(0, BlockInfo[exitID].ExitContext);
1419}
1420
Richard Smith92286672012-02-03 04:45:26 +00001421/// Find the appropriate source locations to use when producing diagnostics for
1422/// each block in the CFG.
1423static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001424 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +00001425 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001426 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +00001427 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1428
1429 // Find the source location of the last statement in the block, if the
1430 // block is not empty.
1431 if (const Stmt *S = CurrBlock->getTerminator()) {
1432 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1433 } else {
1434 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1435 BE = CurrBlock->rend(); BI != BE; ++BI) {
1436 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001437 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1438 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001439 break;
1440 }
1441 }
1442 }
1443
1444 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1445 // This block contains at least one statement. Find the source location
1446 // of the first statement in the block.
1447 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1448 BE = CurrBlock->end(); BI != BE; ++BI) {
1449 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001450 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1451 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001452 break;
1453 }
1454 }
1455 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1456 CurrBlock != &CFGraph->getExit()) {
1457 // The block is empty, and has a single predecessor. Use its exit
1458 // location.
1459 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1460 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1461 }
1462 }
1463}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001464
1465/// \brief Class which implements the core thread safety analysis routines.
1466class ThreadSafetyAnalyzer {
1467 friend class BuildLockset;
1468
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001469 ThreadSafetyHandler &Handler;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001470 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001471 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001472 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001473
1474public:
1475 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1476
Aaron Ballmane0449042014-04-01 21:43:23 +00001477 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat,
1478 StringRef DiagKind);
1479 void removeLock(FactSet &FSet, const SExpr &Mutex, SourceLocation UnlockLoc,
1480 bool FullyRemove, LockKind Kind, StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001481
1482 template <typename AttrType>
1483 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001484 const NamedDecl *D, VarDecl *SelfDecl=0);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001485
1486 template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001487 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1488 const NamedDecl *D,
1489 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1490 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001491
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001492 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1493 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001494
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001495 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1496 const CFGBlock* PredBlock,
1497 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001498
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001499 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1500 SourceLocation JoinLoc,
1501 LockErrorKind LEK1, LockErrorKind LEK2,
1502 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001503
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001504 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1505 SourceLocation JoinLoc, LockErrorKind LEK1,
1506 bool Modify=true) {
1507 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001508 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001509
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001510 void runAnalysis(AnalysisDeclContext &AC);
1511};
1512
Aaron Ballmane0449042014-04-01 21:43:23 +00001513/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
1514static const ValueDecl *getValueDecl(const Expr *Exp) {
1515 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1516 return getValueDecl(CE->getSubExpr());
1517
1518 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1519 return DR->getDecl();
1520
1521 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1522 return ME->getMemberDecl();
1523
1524 return nullptr;
1525}
1526
1527template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001528class has_arg_iterator_range {
Aaron Ballmane0449042014-04-01 21:43:23 +00001529 typedef char yes[1];
1530 typedef char no[2];
1531
1532 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001533 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001534
1535 template <typename>
1536 static no& test(...);
1537
1538public:
1539 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1540};
1541
1542static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1543 return A->getName();
1544}
1545
1546static StringRef ClassifyDiagnostic(QualType VDT) {
1547 // We need to look at the declaration of the type of the value to determine
1548 // which it is. The type should either be a record or a typedef, or a pointer
1549 // or reference thereof.
1550 if (const auto *RT = VDT->getAs<RecordType>()) {
1551 if (const auto *RD = RT->getDecl())
1552 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1553 return ClassifyDiagnostic(CA);
1554 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1555 if (const auto *TD = TT->getDecl())
1556 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1557 return ClassifyDiagnostic(CA);
1558 } else if (VDT->isPointerType() || VDT->isReferenceType())
1559 return ClassifyDiagnostic(VDT->getPointeeType());
1560
1561 return "mutex";
1562}
1563
1564static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1565 assert(VD && "No ValueDecl passed");
1566
1567 // The ValueDecl is the declaration of a mutex or role (hopefully).
1568 return ClassifyDiagnostic(VD->getType());
1569}
1570
1571template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001572static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001573 StringRef>::type
1574ClassifyDiagnostic(const AttrTy *A) {
1575 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1576 return ClassifyDiagnostic(VD);
1577 return "mutex";
1578}
1579
1580template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001581static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001582 StringRef>::type
1583ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001584 for (const auto *Arg : A->args()) {
1585 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +00001586 return ClassifyDiagnostic(VD);
1587 }
1588 return "mutex";
1589}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001590
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001591/// \brief Add a new lock to the lockset, warning if the lock is already there.
1592/// \param Mutex -- the Mutex expression for the lock
1593/// \param LDat -- the LockData for the lock
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001594void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
Aaron Ballmane0449042014-04-01 21:43:23 +00001595 const LockData &LDat, StringRef DiagKind) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001596 // FIXME: deal with acquired before/after annotations.
1597 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001598 if (Mutex.shouldIgnore())
1599 return;
1600
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001601 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001602 if (!LDat.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00001603 Handler.handleDoubleLock(DiagKind, Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001604 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001605 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001606 }
1607}
1608
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001609
1610/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenek78094ca2012-08-22 23:50:41 +00001611/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001612/// \param UnlockLoc The source location of the unlock (only used in error msg)
Aaron Ballmandf115d92014-03-21 14:48:48 +00001613void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001614 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001615 bool FullyRemove, LockKind ReceivedKind,
1616 StringRef DiagKind) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001617 if (Mutex.shouldIgnore())
1618 return;
1619
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001620 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001621 if (!LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001622 Handler.handleUnmatchedUnlock(DiagKind, Mutex.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001623 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001624 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001625
Aaron Ballmandf115d92014-03-21 14:48:48 +00001626 // Generic lock removal doesn't care about lock kind mismatches, but
1627 // otherwise diagnose when the lock kinds are mismatched.
1628 if (ReceivedKind != LK_Generic && LDat->LKind != ReceivedKind) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001629 Handler.handleIncorrectUnlockKind(DiagKind, Mutex.toString(), LDat->LKind,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001630 ReceivedKind, UnlockLoc);
1631 return;
1632 }
1633
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001634 if (LDat->UnderlyingMutex.isValid()) {
1635 // This is scoped lockable object, which manages the real mutex.
1636 if (FullyRemove) {
1637 // We're destroying the managing object.
1638 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001639 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1640 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001641 } else {
1642 // We're releasing the underlying mutex, but not destroying the
1643 // managing object. Warn on dual release.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001644 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001645 Handler.handleUnmatchedUnlock(
1646 DiagKind, LDat->UnderlyingMutex.toString(), UnlockLoc);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001647 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001648 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1649 return;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001650 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001651 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001652 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001653}
1654
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001655
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001656/// \brief Extract the list of mutexIDs from the attribute on an expression,
1657/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001658template <typename AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001659void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001660 Expr *Exp, const NamedDecl *D,
1661 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001662 if (Attr->args_size() == 0) {
1663 // The mutex held is the "this" object.
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001664 SExpr Mu(0, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001665 if (!Mu.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +00001666 SExpr::warnInvalidLock(Handler, 0, Exp, D, ClassifyDiagnostic(Attr));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001667 else
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001668 Mtxs.push_back_nodup(Mu);
1669 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001670 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001671
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001672 for (const auto *Arg : Attr->args()) {
1673 SExpr Mu(Arg, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001674 if (!Mu.isValid())
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001675 SExpr::warnInvalidLock(Handler, Arg, Exp, D, ClassifyDiagnostic(Attr));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001676 else
1677 Mtxs.push_back_nodup(Mu);
1678 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001679}
1680
1681
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001682/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1683/// trylock applies to the given edge, then push them onto Mtxs, discarding
1684/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001685template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001686void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1687 Expr *Exp, const NamedDecl *D,
1688 const CFGBlock *PredBlock,
1689 const CFGBlock *CurrBlock,
1690 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001691 // Find out which branch has the lock
1692 bool branch = 0;
1693 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1694 branch = BLE->getValue();
1695 }
1696 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1697 branch = ILE->getValue().getBoolValue();
1698 }
1699 int branchnum = branch ? 0 : 1;
1700 if (Neg) branchnum = !branchnum;
1701
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001702 // If we've taken the trylock branch, then add the lock
1703 int i = 0;
1704 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1705 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1706 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001707 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001708 }
1709 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001710}
1711
1712
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001713bool getStaticBooleanValue(Expr* E, bool& TCond) {
1714 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1715 TCond = false;
1716 return true;
1717 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1718 TCond = BLE->getValue();
1719 return true;
1720 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1721 TCond = ILE->getValue().getBoolValue();
1722 return true;
1723 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1724 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1725 }
1726 return false;
1727}
1728
1729
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001730// If Cond can be traced back to a function call, return the call expression.
1731// The negate variable should be called with false, and will be set to true
1732// if the function call is negated, e.g. if (!mu.tryLock(...))
1733const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1734 LocalVarContext C,
1735 bool &Negate) {
1736 if (!Cond)
1737 return 0;
1738
1739 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1740 return CallExp;
1741 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001742 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1743 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1744 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001745 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1746 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1747 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001748 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1749 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1750 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001751 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1752 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1753 return getTrylockCallExpr(E, C, Negate);
1754 }
1755 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1756 if (UOP->getOpcode() == UO_LNot) {
1757 Negate = !Negate;
1758 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1759 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001760 return 0;
1761 }
1762 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1763 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1764 if (BOP->getOpcode() == BO_NE)
1765 Negate = !Negate;
1766
1767 bool TCond = false;
1768 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1769 if (!TCond) Negate = !Negate;
1770 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1771 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001772 TCond = false;
1773 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001774 if (!TCond) Negate = !Negate;
1775 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1776 }
1777 return 0;
1778 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001779 if (BOP->getOpcode() == BO_LAnd) {
1780 // LHS must have been evaluated in a different block.
1781 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1782 }
1783 if (BOP->getOpcode() == BO_LOr) {
1784 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1785 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001786 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001787 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001788 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001789}
1790
1791
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001792/// \brief Find the lockset that holds on the edge between PredBlock
1793/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1794/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001795void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1796 const FactSet &ExitSet,
1797 const CFGBlock *PredBlock,
1798 const CFGBlock *CurrBlock) {
1799 Result = ExitSet;
1800
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001801 const Stmt *Cond = PredBlock->getTerminatorCondition();
1802 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001803 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001804
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001805 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001806 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1807 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001808 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001809
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001810 CallExpr *Exp =
1811 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001812 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001813 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001814
1815 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1816 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001817 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001818
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001819 MutexIDList ExclusiveLocksToAdd;
1820 MutexIDList SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001821
1822 // If the condition is a call to a Trylock function, then grab the attributes
1823 AttrVec &ArgAttrs = FunDecl->getAttrs();
1824 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1825 Attr *Attr = ArgAttrs[i];
1826 switch (Attr->getKind()) {
1827 case attr::ExclusiveTrylockFunction: {
1828 ExclusiveTrylockFunctionAttr *A =
1829 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001830 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1831 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001832 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001833 break;
1834 }
1835 case attr::SharedTrylockFunction: {
1836 SharedTrylockFunctionAttr *A =
1837 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001838 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001839 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001840 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001841 break;
1842 }
1843 default:
1844 break;
1845 }
1846 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001847
1848 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001849 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001850 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1851 addLock(Result, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
1852 CapDiagKind);
1853 for (const auto &SharedLockToAdd : SharedLocksToAdd)
1854 addLock(Result, SharedLockToAdd, LockData(Loc, LK_Shared), CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001855}
1856
Caitlin Sadowski33208342011-09-09 16:11:56 +00001857/// \brief We use this class to visit different types of expressions in
1858/// CFGBlocks, and build up the lockset.
1859/// An expression may cause us to add or remove locks from the lockset, or else
1860/// output error messages related to missing locks.
1861/// FIXME: In future, we may be able to not inherit from a visitor.
1862class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001863 friend class ThreadSafetyAnalyzer;
1864
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001865 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001866 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001867 LocalVariableMap::Context LVarCtx;
1868 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001869
1870 // Helper functions
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001871
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001872 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001873 Expr *MutexExp, ProtectedOperationKind POK,
1874 StringRef DiagKind);
1875 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1876 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001877
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001878 void checkAccess(const Expr *Exp, AccessKind AK);
1879 void checkPtAccess(const Expr *Exp, AccessKind AK);
1880
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001881 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001882
Caitlin Sadowski33208342011-09-09 16:11:56 +00001883public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001884 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001885 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001886 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001887 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001888 LVarCtx(Info.EntryContext),
1889 CtxIndex(Info.EntryIndex)
1890 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001891
1892 void VisitUnaryOperator(UnaryOperator *UO);
1893 void VisitBinaryOperator(BinaryOperator *BO);
1894 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001895 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001896 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001897 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001898};
1899
Caitlin Sadowski33208342011-09-09 16:11:56 +00001900/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001901/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001902void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001903 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001904 ProtectedOperationKind POK,
1905 StringRef DiagKind) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001906 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001907
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001908 SExpr Mutex(MutexExp, Exp, D);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001909 if (!Mutex.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001910 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001911 return;
1912 } else if (Mutex.shouldIgnore()) {
1913 return;
1914 }
1915
1916 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001917 bool NoError = true;
1918 if (!LDat) {
1919 // No exact match found. Look for a partial match.
1920 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1921 if (FEntry) {
1922 // Warn that there's no precise match.
1923 LDat = &FEntry->LDat;
1924 std::string PartMatchStr = FEntry->MutID.toString();
1925 StringRef PartMatchName(PartMatchStr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001926 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1927 LK, Exp->getExprLoc(),
1928 &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001929 } else {
1930 // Warn that there's no match at all.
Aaron Ballmane0449042014-04-01 21:43:23 +00001931 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1932 LK, Exp->getExprLoc());
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001933 }
1934 NoError = false;
1935 }
1936 // Make sure the mutex we found is the right kind.
1937 if (NoError && LDat && !LDat->isAtLeast(LK))
Aaron Ballmane0449042014-04-01 21:43:23 +00001938 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(), LK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001939 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001940}
1941
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001942/// \brief Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001943void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1944 Expr *MutexExp,
1945 StringRef DiagKind) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001946 SExpr Mutex(MutexExp, Exp, D);
1947 if (!Mutex.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001948 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001949 return;
1950 }
1951
1952 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
Aaron Ballmane0449042014-04-01 21:43:23 +00001953 if (LDat)
1954 Analyzer->Handler.handleFunExcludesLock(
1955 DiagKind, D->getNameAsString(), Mutex.toString(), Exp->getExprLoc());
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001956}
1957
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001958/// \brief Checks guarded_by and pt_guarded_by attributes.
1959/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1960/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1961/// Similarly, we check if the access is to an expression that dereferences
1962/// a pointer marked with pt_guarded_by.
1963void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1964 Exp = Exp->IgnoreParenCasts();
1965
1966 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1967 // For dereferences
1968 if (UO->getOpcode() == clang::UO_Deref)
1969 checkPtAccess(UO->getSubExpr(), AK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001970 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001971 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001972
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001973 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001974 checkPtAccess(AE->getLHS(), AK);
1975 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001976 }
1977
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001978 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1979 if (ME->isArrow())
1980 checkPtAccess(ME->getBase(), AK);
1981 else
1982 checkAccess(ME->getBase(), AK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001983 }
1984
Caitlin Sadowski33208342011-09-09 16:11:56 +00001985 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001986 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001987 return;
1988
Aaron Ballman9ead1242013-12-19 02:39:40 +00001989 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00001990 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarAccess, AK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001991 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001992
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001993 for (const auto *I : D->specific_attrs<GuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00001994 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarAccess,
1995 ClassifyDiagnostic(I));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001996}
1997
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001998/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1999void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00002000 while (true) {
2001 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
2002 Exp = PE->getSubExpr();
2003 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002004 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00002005 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
2006 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
2007 // If it's an actual array, and not a pointer, then it's elements
2008 // are protected by GUARDED_BY, not PT_GUARDED_BY;
2009 checkAccess(CE->getSubExpr(), AK);
2010 return;
2011 }
2012 Exp = CE->getSubExpr();
2013 continue;
2014 }
2015 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002016 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002017
2018 const ValueDecl *D = getValueDecl(Exp);
2019 if (!D || !D->hasAttrs())
2020 return;
2021
Aaron Ballman9ead1242013-12-19 02:39:40 +00002022 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00002023 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarDereference, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002024 Exp->getExprLoc());
2025
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002026 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00002027 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarDereference,
2028 ClassifyDiagnostic(I));
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002029}
2030
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002031/// \brief Process a function call, method call, constructor call,
2032/// or destructor call. This involves looking at the attributes on the
2033/// corresponding function/method/constructor/destructor, issuing warnings,
2034/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002035///
2036/// FIXME: For classes annotated with one of the guarded annotations, we need
2037/// to treat const method calls as reads and non-const method calls as writes,
2038/// and check that the appropriate locks are held. Non-const method calls with
2039/// the same signature as const method calls can be also treated as reads.
2040///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002041void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002042 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002043 const AttrVec &ArgAttrs = D->getAttrs();
Aaron Ballmandf115d92014-03-21 14:48:48 +00002044 MutexIDList ExclusiveLocksToAdd, SharedLocksToAdd;
2045 MutexIDList ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
Aaron Ballmane0449042014-04-01 21:43:23 +00002046 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002047
Caitlin Sadowski33208342011-09-09 16:11:56 +00002048 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002049 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
2050 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002051 // When we encounter a lock function, we need to add the lock to our
2052 // lockset.
2053 case attr::AcquireCapability: {
2054 auto *A = cast<AcquireCapabilityAttr>(At);
2055 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
2056 : ExclusiveLocksToAdd,
2057 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002058
2059 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002060 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002061 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002062
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002063 // An assert will add a lock to the lockset, but will not generate
2064 // a warning if it is already there, and will not generate a warning
2065 // if it is not removed.
2066 case attr::AssertExclusiveLock: {
2067 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
2068
2069 MutexIDList AssertLocks;
2070 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002071 for (const auto &AssertLock : AssertLocks)
2072 Analyzer->addLock(FSet, AssertLock,
2073 LockData(Loc, LK_Exclusive, false, true),
2074 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002075 break;
2076 }
2077 case attr::AssertSharedLock: {
2078 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
2079
2080 MutexIDList AssertLocks;
2081 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002082 for (const auto &AssertLock : AssertLocks)
2083 Analyzer->addLock(FSet, AssertLock,
2084 LockData(Loc, LK_Shared, false, true),
2085 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002086 break;
2087 }
2088
Caitlin Sadowski33208342011-09-09 16:11:56 +00002089 // When we encounter an unlock function, we need to remove unlocked
2090 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002091 case attr::ReleaseCapability: {
2092 auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002093 if (A->isGeneric())
2094 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
2095 else if (A->isShared())
2096 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
2097 else
2098 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002099
2100 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002101 break;
2102 }
2103
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002104 case attr::RequiresCapability: {
2105 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00002106 for (auto *Arg : A->args())
2107 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
Aaron Ballmane0449042014-04-01 21:43:23 +00002108 POK_FunctionCall, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002109 break;
2110 }
2111
2112 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002113 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00002114 for (auto *Arg : A->args())
2115 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002116 break;
2117 }
2118
Alp Tokerd4733632013-12-05 04:47:09 +00002119 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00002120 default:
2121 break;
2122 }
2123 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002124
2125 // Figure out if we're calling the constructor of scoped lockable class
2126 bool isScopedVar = false;
2127 if (VD) {
2128 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
2129 const CXXRecordDecl* PD = CD->getParent();
Aaron Ballman9ead1242013-12-19 02:39:40 +00002130 if (PD && PD->hasAttr<ScopedLockableAttr>())
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002131 isScopedVar = true;
2132 }
2133 }
2134
2135 // Add locks.
Aaron Ballmandf115d92014-03-21 14:48:48 +00002136 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002137 Analyzer->addLock(FSet, M, LockData(Loc, LK_Exclusive, isScopedVar),
2138 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002139 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002140 Analyzer->addLock(FSet, M, LockData(Loc, LK_Shared, isScopedVar),
2141 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002142
2143 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
2144 // FIXME -- this doesn't work if we acquire multiple locks.
2145 if (isScopedVar) {
2146 SourceLocation MLoc = VD->getLocation();
2147 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002148 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002149
Aaron Ballmandf115d92014-03-21 14:48:48 +00002150 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002151 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive, M),
2152 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002153 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002154 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared, M),
2155 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002156 }
2157
2158 // Remove locks.
2159 // FIXME -- should only fully remove if the attribute refers to 'this'.
2160 bool Dtor = isa<CXXDestructorDecl>(D);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002161 for (const auto &M : ExclusiveLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002162 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002163 for (const auto &M : SharedLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002164 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002165 for (const auto &M : GenericLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002166 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002167}
2168
DeLesley Hutchins9d530332012-01-06 19:16:50 +00002169
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002170/// \brief For unary operations which read and write a variable, we need to
2171/// check whether we hold any required mutexes. Reads are checked in
2172/// VisitCastExpr.
2173void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
2174 switch (UO->getOpcode()) {
2175 case clang::UO_PostDec:
2176 case clang::UO_PostInc:
2177 case clang::UO_PreDec:
2178 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002179 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002180 break;
2181 }
2182 default:
2183 break;
2184 }
2185}
2186
2187/// For binary operations which assign to a variable (writes), we need to check
2188/// whether we hold any required mutexes.
2189/// FIXME: Deal with non-primitive types.
2190void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2191 if (!BO->isAssignmentOp())
2192 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002193
2194 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002195 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002196
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002197 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002198}
2199
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002200
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002201/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2202/// need to ensure we hold any required mutexes.
2203/// FIXME: Deal with non-primitive types.
2204void BuildLockset::VisitCastExpr(CastExpr *CE) {
2205 if (CE->getCastKind() != CK_LValueToRValue)
2206 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002207 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002208}
2209
2210
DeLesley Hutchins714296c2011-12-29 00:56:48 +00002211void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002212 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2213 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
2214 // ME can be null when calling a method pointer
2215 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002216
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002217 if (ME && MD) {
2218 if (ME->isArrow()) {
2219 if (MD->isConst()) {
2220 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2221 } else { // FIXME -- should be AK_Written
2222 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002223 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002224 } else {
2225 if (MD->isConst())
2226 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2227 else // FIXME -- should be AK_Written
2228 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002229 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002230 }
2231 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2232 switch (OE->getOperator()) {
2233 case OO_Equal: {
2234 const Expr *Target = OE->getArg(0);
2235 const Expr *Source = OE->getArg(1);
2236 checkAccess(Target, AK_Written);
2237 checkAccess(Source, AK_Read);
2238 break;
2239 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002240 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002241 case OO_Arrow:
2242 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00002243 const Expr *Obj = OE->getArg(0);
2244 checkAccess(Obj, AK_Read);
2245 checkPtAccess(Obj, AK_Read);
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002246 break;
2247 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002248 default: {
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00002249 const Expr *Obj = OE->getArg(0);
2250 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002251 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002252 }
2253 }
2254 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002255 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2256 if(!D || !D->hasAttrs())
2257 return;
2258 handleCall(Exp, D);
2259}
2260
2261void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002262 const CXXConstructorDecl *D = Exp->getConstructor();
2263 if (D && D->isCopyConstructor()) {
2264 const Expr* Source = Exp->getArg(0);
2265 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002266 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002267 // FIXME -- only handles constructors in DeclStmt below.
2268}
2269
2270void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002271 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002272 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002273
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002274 DeclGroupRef DGrp = S->getDeclGroup();
2275 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2276 Decl *D = *I;
2277 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2278 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002279 // handle constructors that involve temporaries
2280 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2281 E = EWC->getSubExpr();
2282
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002283 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2284 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2285 if (!CtorD || !CtorD->hasAttrs())
2286 return;
2287 handleCall(CE, CtorD, VD);
2288 }
2289 }
2290 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002291}
2292
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002293
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002294
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002295/// \brief Compute the intersection of two locksets and issue warnings for any
2296/// locks in the symmetric difference.
2297///
2298/// This function is used at a merge point in the CFG when comparing the lockset
2299/// of each branch being merged. For example, given the following sequence:
2300/// A; if () then B; else C; D; we need to check that the lockset after B and C
2301/// are the same. In the event of a difference, we use the intersection of these
2302/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002303///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002304/// \param FSet1 The first lockset.
2305/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002306/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002307/// \param LEK1 The error message to report if a mutex is missing from LSet1
2308/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002309void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2310 const FactSet &FSet2,
2311 SourceLocation JoinLoc,
2312 LockErrorKind LEK1,
2313 LockErrorKind LEK2,
2314 bool Modify) {
2315 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002316
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002317 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002318 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2319 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002320 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002321 const LockData &LDat2 = FactMan[*I].LDat;
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002322 FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002323
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002324 if (I1 != FSet1.end()) {
2325 const LockData* LDat1 = &FactMan[*I1].LDat;
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002326 if (LDat1->LKind != LDat2.LKind) {
Aaron Ballmane0449042014-04-01 21:43:23 +00002327 Handler.handleExclusiveAndShared("mutex", FSet2Mutex.toString(),
2328 LDat2.AcquireLoc, LDat1->AcquireLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002329 if (Modify && LDat1->LKind != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002330 // Take the exclusive lock, which is the one in FSet2.
2331 *I1 = *I;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002332 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002333 }
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002334 else if (LDat1->Asserted && !LDat2.Asserted) {
2335 // The non-asserted lock in FSet2 is the one we want to track.
2336 *I1 = *I;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002337 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002338 } else {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002339 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002340 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002341 // If this is a scoped lock that manages another mutex, and if the
2342 // underlying mutex is still held, then warn about the underlying
2343 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00002344 Handler.handleMutexHeldEndOfScope("mutex",
2345 LDat2.UnderlyingMutex.toString(),
2346 LDat2.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002347 }
2348 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002349 else if (!LDat2.Managed && !FSet2Mutex.isUniversal() && !LDat2.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00002350 Handler.handleMutexHeldEndOfScope("mutex", FSet2Mutex.toString(),
2351 LDat2.AcquireLoc, JoinLoc, LEK1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002352 }
2353 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002354
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002355 // Find locks in FSet1 that are not in FSet2, and remove them.
2356 for (FactSet::const_iterator I = FSet1Orig.begin(), E = FSet1Orig.end();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002357 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002358 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002359 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002360
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002361 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002362 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002363 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002364 // If this is a scoped lock that manages another mutex, and if the
2365 // underlying mutex is still held, then warn about the underlying
2366 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00002367 Handler.handleMutexHeldEndOfScope("mutex",
2368 LDat1.UnderlyingMutex.toString(),
2369 LDat1.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002370 }
2371 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002372 else if (!LDat1.Managed && !FSet1Mutex.isUniversal() && !LDat1.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00002373 Handler.handleMutexHeldEndOfScope("mutex", FSet1Mutex.toString(),
2374 LDat1.AcquireLoc, JoinLoc, LEK2);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002375 if (Modify)
2376 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002377 }
2378 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002379}
2380
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002381
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002382// Return true if block B never continues to its successors.
2383inline bool neverReturns(const CFGBlock* B) {
2384 if (B->hasNoReturnElement())
2385 return true;
2386 if (B->empty())
2387 return false;
2388
2389 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002390 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2391 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002392 return true;
2393 }
2394 return false;
2395}
2396
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002397
Caitlin Sadowski33208342011-09-09 16:11:56 +00002398/// \brief Check a function's CFG for thread-safety violations.
2399///
2400/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2401/// at the end of each block, and issue warnings for thread safety violations.
2402/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002403void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002404 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2405 // For now, we just use the walker to set things up.
2406 threadSafety::CFGWalker walker;
2407 if (!walker.init(AC))
2408 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002409
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002410 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002411 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002412
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002413 CFG *CFGraph = walker.getGraph();
2414 const NamedDecl *D = walker.getDecl();
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002415
Aaron Ballman9ead1242013-12-19 02:39:40 +00002416 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002417 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002418
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002419 // FIXME: Do something a bit more intelligent inside constructor and
2420 // destructor code. Constructors and destructors must assume unique access
2421 // to 'this', so checks on member variable access is disabled, but we should
2422 // still enable checks on other objects.
2423 if (isa<CXXConstructorDecl>(D))
2424 return; // Don't check inside constructors.
2425 if (isa<CXXDestructorDecl>(D))
2426 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002427
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002428 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002429 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002430
2431 // We need to explore the CFG via a "topological" ordering.
2432 // That way, we will be guaranteed to have information about required
2433 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002434 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002435 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002436
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002437 // Mark entry block as reachable
2438 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2439
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002440 // Compute SSA names for local variables
2441 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2442
Richard Smith92286672012-02-03 04:45:26 +00002443 // Fill in source locations for all CFGBlocks.
2444 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2445
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002446 MutexIDList ExclusiveLocksAcquired;
2447 MutexIDList SharedLocksAcquired;
2448 MutexIDList LocksReleased;
2449
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002450 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002451 // to initial lockset. Also turn off checking for lock and unlock functions.
2452 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002453 if (!SortedGraph->empty() && D->hasAttrs()) {
2454 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002455 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002456 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002457
2458 MutexIDList ExclusiveLocksToAdd;
2459 MutexIDList SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002460 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002461
2462 SourceLocation Loc = D->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002463 for (const auto *Attr : ArgAttrs) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002464 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002465 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002466 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2467 0, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002468 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002469 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002470 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2471 // We must ignore such methods.
2472 if (A->args_size() == 0)
2473 return;
2474 // FIXME -- deal with exclusive vs. shared unlock functions?
Aaron Ballman0491afa2014-04-18 13:13:15 +00002475 getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
2476 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002477 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002478 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002479 if (A->args_size() == 0)
2480 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002481 getMutexIDs(A->isShared() ? SharedLocksAcquired
2482 : ExclusiveLocksAcquired,
2483 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002484 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002485 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2486 // Don't try to check trylock functions for now
2487 return;
2488 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2489 // Don't try to check trylock functions for now
2490 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002491 }
2492 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002493
2494 // FIXME -- Loc can be wrong here.
Aaron Ballmane0449042014-04-01 21:43:23 +00002495 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
2496 addLock(InitialLockset, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
2497 CapDiagKind);
2498 for (const auto &SharedLockToAdd : SharedLocksToAdd)
2499 addLock(InitialLockset, SharedLockToAdd, LockData(Loc, LK_Shared),
2500 CapDiagKind);
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002501 }
2502
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002503 for (const auto *CurrBlock : *SortedGraph) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002504 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002505 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002506
2507 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002508 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002509
2510 // Iterate through the predecessor blocks and warn if the lockset for all
2511 // predecessors is not the same. We take the entry lockset of the current
2512 // block to be the intersection of all previous locksets.
2513 // FIXME: By keeping the intersection, we may output more errors in future
2514 // for a lock which is not in the intersection, but was in the union. We
2515 // may want to also keep the union in future. As an example, let's say
2516 // the intersection contains Mutex L, and the union contains L and M.
2517 // Later we unlock M. At this point, we would output an error because we
2518 // never locked M; although the real error is probably that we forgot to
2519 // lock M on all code paths. Conversely, let's say that later we lock M.
2520 // In this case, we should compare against the intersection instead of the
2521 // union because the real error is probably that we forgot to unlock M on
2522 // all code paths.
2523 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002524 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002525 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2526 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2527
2528 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002529 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002530 continue;
2531
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002532 int PrevBlockID = (*PI)->getBlockID();
2533 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2534
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002535 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002536 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002537 continue;
2538
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002539 // Okay, we can reach this block from the entry.
2540 CurrBlockInfo->Reachable = true;
2541
Richard Smith815b29d2012-02-03 03:30:07 +00002542 // If the previous block ended in a 'continue' or 'break' statement, then
2543 // a difference in locksets is probably due to a bug in that block, rather
2544 // than in some other predecessor. In that case, keep the other
2545 // predecessor's lockset.
2546 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2547 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2548 SpecialBlocks.push_back(*PI);
2549 continue;
2550 }
2551 }
2552
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002553 FactSet PrevLockset;
2554 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002555
Caitlin Sadowski33208342011-09-09 16:11:56 +00002556 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002557 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002558 LocksetInitialized = true;
2559 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002560 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2561 CurrBlockInfo->EntryLoc,
2562 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002563 }
2564 }
2565
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002566 // Skip rest of block if it's not reachable.
2567 if (!CurrBlockInfo->Reachable)
2568 continue;
2569
Richard Smith815b29d2012-02-03 03:30:07 +00002570 // Process continue and break blocks. Assume that the lockset for the
2571 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002572 for (const auto *PrevBlock : SpecialBlocks) {
Richard Smith815b29d2012-02-03 03:30:07 +00002573 int PrevBlockID = PrevBlock->getBlockID();
2574 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2575
2576 if (!LocksetInitialized) {
2577 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2578 LocksetInitialized = true;
2579 } else {
2580 // Determine whether this edge is a loop terminator for diagnostic
2581 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2582 // it might also be part of a switch. Also, a subsequent destructor
2583 // might add to the lockset, in which case the real issue might be a
2584 // double lock on the other path.
2585 const Stmt *Terminator = PrevBlock->getTerminator();
2586 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2587
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002588 FactSet PrevLockset;
2589 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2590 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002591
Richard Smith815b29d2012-02-03 03:30:07 +00002592 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002593 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2594 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002595 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002596 : LEK_LockedSomePredecessors,
2597 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002598 }
2599 }
2600
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002601 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2602
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002603 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002604 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2605 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002606 switch (BI->getKind()) {
2607 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002608 CFGStmt CS = BI->castAs<CFGStmt>();
2609 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002610 break;
2611 }
2612 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2613 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002614 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2615 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2616 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002617 if (!DD->hasAttrs())
2618 break;
2619
2620 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002621 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
John McCall113bee02012-03-10 09:33:50 +00002622 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002623 AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002624 LocksetBuilder.handleCall(&DRE, DD);
2625 break;
2626 }
2627 default:
2628 break;
2629 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002630 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002631 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002632
2633 // For every back edge from CurrBlock (the end of the loop) to another block
2634 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2635 // the one held at the beginning of FirstLoopBlock. We can look up the
2636 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2637 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2638 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2639
2640 // if CurrBlock -> *SI is *not* a back edge
2641 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2642 continue;
2643
2644 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002645 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2646 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2647 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2648 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002649 LEK_LockedSomeLoopIterations,
2650 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002651 }
2652 }
2653
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002654 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2655 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002656
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002657 // Skip the final check if the exit block is unreachable.
2658 if (!Final->Reachable)
2659 return;
2660
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002661 // By default, we expect all locks held on entry to be held on exit.
2662 FactSet ExpectedExitSet = Initial->EntrySet;
2663
2664 // Adjust the expected exit set by adding or removing locks, as declared
2665 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2666 // issue the appropriate warning.
2667 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002668 for (const auto &Lock : ExclusiveLocksAcquired)
2669 ExpectedExitSet.addLock(FactMan, Lock,
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002670 LockData(D->getLocation(), LK_Exclusive));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002671 for (const auto &Lock : SharedLocksAcquired)
2672 ExpectedExitSet.addLock(FactMan, Lock,
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002673 LockData(D->getLocation(), LK_Shared));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002674 for (const auto &Lock : LocksReleased)
2675 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002676
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002677 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002678 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002679 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002680 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002681 LEK_NotLockedAtEndOfFunction,
2682 false);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002683}
2684
2685} // end anonymous namespace
2686
2687
2688namespace clang {
2689namespace thread_safety {
2690
2691/// \brief Check a function's CFG for thread-safety violations.
2692///
2693/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2694/// at the end of each block, and issue warnings for thread safety violations.
2695/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002696void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002697 ThreadSafetyHandler &Handler) {
2698 ThreadSafetyAnalyzer Analyzer(Handler);
2699 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002700}
2701
2702/// \brief Helper function that returns a LockKind required for the given level
2703/// of access.
2704LockKind getLockKindFromAccessKind(AccessKind AK) {
2705 switch (AK) {
2706 case AK_Read :
2707 return LK_Shared;
2708 case AK_Written :
2709 return LK_Exclusive;
2710 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002711 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002712}
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002713
Caitlin Sadowski33208342011-09-09 16:11:56 +00002714}} // end namespace clang::thread_safety