blob: 075324da5f54247c93531a163e8cbdae1c7ff415 [file] [log] [blame]
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001//===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A intra-procedural analysis for thread safety (e.g. deadlocks and race
11// conditions), based off of an annotation system.
12//
Caitlin Sadowski19903462011-09-14 20:05:09 +000013// See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
14// information.
Caitlin Sadowski402aa062011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek439ed162011-10-22 02:14:27 +000019#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000020#include "clang/Analysis/AnalysisContext.h"
21#include "clang/Analysis/CFG.h"
22#include "clang/Analysis/CFGStmtMap.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000023#include "clang/AST/DeclCXX.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtVisitor.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceLocation.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/FoldingSet.h"
31#include "llvm/ADT/ImmutableMap.h"
32#include "llvm/ADT/PostOrderIterator.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringRef.h"
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000035#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000036#include <algorithm>
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000037#include <utility>
Caitlin Sadowski402aa062011-09-09 16:11:56 +000038#include <vector>
39
40using namespace clang;
41using namespace thread_safety;
42
Caitlin Sadowski19903462011-09-14 20:05:09 +000043// Key method definition
44ThreadSafetyHandler::~ThreadSafetyHandler() {}
45
Caitlin Sadowski402aa062011-09-09 16:11:56 +000046namespace {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +000047
Caitlin Sadowski402aa062011-09-09 16:11:56 +000048/// \brief A MutexID object uniquely identifies a particular mutex, and
49/// is built from an Expr* (i.e. calling a lock function).
50///
51/// Thread-safety analysis works by comparing lock expressions. Within the
52/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
53/// a particular mutex object at run-time. Subsequent occurrences of the same
54/// expression (where "same" means syntactic equality) will refer to the same
55/// run-time object if three conditions hold:
56/// (1) Local variables in the expression, such as "x" have not changed.
57/// (2) Values on the heap that affect the expression have not changed.
58/// (3) The expression involves only pure function calls.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +000059///
Caitlin Sadowski402aa062011-09-09 16:11:56 +000060/// The current implementation assumes, but does not verify, that multiple uses
61/// of the same lock expression satisfies these criteria.
62///
63/// Clang introduces an additional wrinkle, which is that it is difficult to
64/// derive canonical expressions, or compare expressions directly for equality.
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +000065/// Thus, we identify a mutex not by an Expr, but by the list of named
Caitlin Sadowski402aa062011-09-09 16:11:56 +000066/// declarations that are referenced by the Expr. In other words,
67/// x->foo->bar.mu will be a four element vector with the Decls for
68/// mu, bar, and foo, and x. The vector will uniquely identify the expression
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +000069/// for all practical purposes. Null is used to denote 'this'.
Caitlin Sadowski402aa062011-09-09 16:11:56 +000070///
71/// Note we will need to perform substitution on "this" and function parameter
72/// names when constructing a lock expression.
73///
74/// For example:
75/// class C { Mutex Mu; void lock() EXCLUSIVE_LOCK_FUNCTION(this->Mu); };
76/// void myFunc(C *X) { ... X->lock() ... }
77/// The original expression for the mutex acquired by myFunc is "this->Mu", but
78/// "X" is substituted for "this" so we get X->Mu();
79///
80/// For another example:
81/// foo(MyList *L) EXCLUSIVE_LOCKS_REQUIRED(L->Mu) { ... }
82/// MyList *MyL;
83/// foo(MyL); // requires lock MyL->Mu to be held
84class MutexID {
85 SmallVector<NamedDecl*, 2> DeclSeq;
86
87 /// Build a Decl sequence representing the lock from the given expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +000088 /// Recursive function that terminates on DeclRefExpr.
89 /// Note: this function merely creates a MutexID; it does not check to
90 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +000091 void buildMutexID(Expr *Exp, const NamedDecl *D, Expr *Parent,
92 unsigned NumArgs, Expr **FunArgs) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +000093 if (!Exp) {
94 DeclSeq.clear();
95 return;
96 }
97
Caitlin Sadowski402aa062011-09-09 16:11:56 +000098 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
99 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000100 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
101 if (PV) {
102 FunctionDecl *FD =
103 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
104 unsigned i = PV->getFunctionScopeIndex();
105
106 if (FunArgs && FD == D->getCanonicalDecl()) {
107 // Substitute call arguments for references to function parameters
108 assert(i < NumArgs);
109 buildMutexID(FunArgs[i], D, 0, 0, 0);
110 return;
111 }
112 // Map the param back to the param of the original function declaration.
113 DeclSeq.push_back(FD->getParamDecl(i));
114 return;
115 }
116 // Not a function parameter -- just store the reference.
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000117 DeclSeq.push_back(ND);
118 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
119 NamedDecl *ND = ME->getMemberDecl();
120 DeclSeq.push_back(ND);
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000121 buildMutexID(ME->getBase(), D, Parent, NumArgs, FunArgs);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000122 } else if (isa<CXXThisExpr>(Exp)) {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000123 if (Parent)
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000124 buildMutexID(Parent, D, 0, 0, 0);
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000125 else {
126 DeclSeq.push_back(0); // Use 0 to represent 'this'.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000127 return; // mutexID is still valid in this case
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000128 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000129 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
130 DeclSeq.push_back(CMCE->getMethodDecl()->getCanonicalDecl());
131 buildMutexID(CMCE->getImplicitObjectArgument(),
132 D, Parent, NumArgs, FunArgs);
133 unsigned NumCallArgs = CMCE->getNumArgs();
134 Expr** CallArgs = CMCE->getArgs();
135 for (unsigned i = 0; i < NumCallArgs; ++i) {
136 buildMutexID(CallArgs[i], D, Parent, NumArgs, FunArgs);
137 }
138 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
139 buildMutexID(CE->getCallee(), D, Parent, NumArgs, FunArgs);
140 unsigned NumCallArgs = CE->getNumArgs();
141 Expr** CallArgs = CE->getArgs();
142 for (unsigned i = 0; i < NumCallArgs; ++i) {
143 buildMutexID(CallArgs[i], D, Parent, NumArgs, FunArgs);
144 }
145 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
146 buildMutexID(BOE->getLHS(), D, Parent, NumArgs, FunArgs);
147 buildMutexID(BOE->getRHS(), D, Parent, NumArgs, FunArgs);
148 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000149 buildMutexID(UOE->getSubExpr(), D, Parent, NumArgs, FunArgs);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000150 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
151 buildMutexID(ASE->getBase(), D, Parent, NumArgs, FunArgs);
152 buildMutexID(ASE->getIdx(), D, Parent, NumArgs, FunArgs);
153 } else if (AbstractConditionalOperator *CE =
154 dyn_cast<AbstractConditionalOperator>(Exp)) {
155 buildMutexID(CE->getCond(), D, Parent, NumArgs, FunArgs);
156 buildMutexID(CE->getTrueExpr(), D, Parent, NumArgs, FunArgs);
157 buildMutexID(CE->getFalseExpr(), D, Parent, NumArgs, FunArgs);
158 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
159 buildMutexID(CE->getCond(), D, Parent, NumArgs, FunArgs);
160 buildMutexID(CE->getLHS(), D, Parent, NumArgs, FunArgs);
161 buildMutexID(CE->getRHS(), D, Parent, NumArgs, FunArgs);
162 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000163 buildMutexID(CE->getSubExpr(), D, Parent, NumArgs, FunArgs);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000164 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
165 buildMutexID(PE->getSubExpr(), D, Parent, NumArgs, FunArgs);
166 } else if (isa<CharacterLiteral>(Exp) ||
167 isa<CXXNullPtrLiteralExpr>(Exp) ||
168 isa<GNUNullExpr>(Exp) ||
169 isa<CXXBoolLiteralExpr>(Exp) ||
170 isa<FloatingLiteral>(Exp) ||
171 isa<ImaginaryLiteral>(Exp) ||
172 isa<IntegerLiteral>(Exp) ||
173 isa<StringLiteral>(Exp) ||
174 isa<ObjCStringLiteral>(Exp)) {
175 return; // FIXME: Ignore literals for now
176 } else {
177 // Ignore. FIXME: mark as invalid expression?
178 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000179 }
180
181 /// \brief Construct a MutexID from an expression.
182 /// \param MutexExp The original mutex expression within an attribute
183 /// \param DeclExp An expression involving the Decl on which the attribute
184 /// occurs.
185 /// \param D The declaration to which the lock/unlock attribute is attached.
186 void buildMutexIDFromExp(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
187 Expr *Parent = 0;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000188 unsigned NumArgs = 0;
189 Expr **FunArgs = 0;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000190
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000191 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000192 if (DeclExp == 0) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000193 buildMutexID(MutexExp, D, 0, 0, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000194 return;
195 }
196
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000197 // Examine DeclExp to find Parent and FunArgs, which are used to substitute
198 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000199 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000200 Parent = ME->getBase();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000201 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000202 Parent = CE->getImplicitObjectArgument();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000203 NumArgs = CE->getNumArgs();
204 FunArgs = CE->getArgs();
DeLesley Hutchinsdf497822011-12-29 00:56:48 +0000205 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
206 NumArgs = CE->getNumArgs();
207 FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000208 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
209 Parent = 0; // FIXME -- get the parent from DeclStmt
210 NumArgs = CE->getNumArgs();
211 FunArgs = CE->getArgs();
DeLesley Hutchins6db51f72011-10-21 20:51:27 +0000212 } else if (D && isa<CXXDestructorDecl>(D)) {
213 // There's no such thing as a "destructor call" in the AST.
214 Parent = DeclExp;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000215 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000216
217 // If the attribute has no arguments, then assume the argument is "this".
218 if (MutexExp == 0) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000219 buildMutexID(Parent, D, 0, 0, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000220 return;
221 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000222
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000223 buildMutexID(MutexExp, D, Parent, NumArgs, FunArgs);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000224 }
225
226public:
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000227 explicit MutexID(clang::Decl::EmptyShell e) {
228 DeclSeq.clear();
229 }
230
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000231 /// \param MutexExp The original mutex expression within an attribute
232 /// \param DeclExp An expression involving the Decl on which the attribute
233 /// occurs.
234 /// \param D The declaration to which the lock/unlock attribute is attached.
235 /// Caller must check isValid() after construction.
236 MutexID(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
237 buildMutexIDFromExp(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000238 }
239
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000240 /// Return true if this is a valid decl sequence.
241 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000242 bool isValid() const {
243 return !DeclSeq.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000244 }
245
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000246 /// Issue a warning about an invalid lock expression
247 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
248 Expr *DeclExp, const NamedDecl* D) {
249 SourceLocation Loc;
250 if (DeclExp)
251 Loc = DeclExp->getExprLoc();
252
253 // FIXME: add a note about the attribute location in MutexExp or D
254 if (Loc.isValid())
255 Handler.handleInvalidLockExp(Loc);
256 }
257
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000258 bool operator==(const MutexID &other) const {
259 return DeclSeq == other.DeclSeq;
260 }
261
262 bool operator!=(const MutexID &other) const {
263 return !(*this == other);
264 }
265
266 // SmallVector overloads Operator< to do lexicographic ordering. Note that
267 // we use pointer equality (and <) to compare NamedDecls. This means the order
268 // of MutexIDs in a lockset is nondeterministic. In order to output
269 // diagnostics in a deterministic ordering, we must order all diagnostics to
270 // output by SourceLocation when iterating through this lockset.
271 bool operator<(const MutexID &other) const {
272 return DeclSeq < other.DeclSeq;
273 }
274
275 /// \brief Returns the name of the first Decl in the list for a given MutexID;
276 /// e.g. the lock expression foo.bar() has name "bar".
277 /// The caret will point unambiguously to the lock expression, so using this
278 /// name in diagnostics is a way to get simple, and consistent, mutex names.
279 /// We do not want to output the entire expression text for security reasons.
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000280 std::string getName() const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000281 assert(isValid());
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000282 if (!DeclSeq.front())
283 return "this"; // Use 0 to represent 'this'.
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000284 return DeclSeq.front()->getNameAsString();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000285 }
286
287 void Profile(llvm::FoldingSetNodeID &ID) const {
288 for (SmallVectorImpl<NamedDecl*>::const_iterator I = DeclSeq.begin(),
289 E = DeclSeq.end(); I != E; ++I) {
290 ID.AddPointer(*I);
291 }
292 }
293};
294
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000295
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000296/// \brief This is a helper class that stores info about the most recent
297/// accquire of a Lock.
298///
299/// The main body of the analysis maps MutexIDs to LockDatas.
300struct LockData {
301 SourceLocation AcquireLoc;
302
303 /// \brief LKind stores whether a lock is held shared or exclusively.
304 /// Note that this analysis does not currently support either re-entrant
305 /// locking or lock "upgrading" and "downgrading" between exclusive and
306 /// shared.
307 ///
308 /// FIXME: add support for re-entrant locking and lock up/downgrading
309 LockKind LKind;
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000310 MutexID UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000311
312 LockData(SourceLocation AcquireLoc, LockKind LKind)
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000313 : AcquireLoc(AcquireLoc), LKind(LKind), UnderlyingMutex(Decl::EmptyShell())
314 {}
315
316 LockData(SourceLocation AcquireLoc, LockKind LKind, const MutexID &Mu)
317 : AcquireLoc(AcquireLoc), LKind(LKind), UnderlyingMutex(Mu) {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000318
319 bool operator==(const LockData &other) const {
320 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
321 }
322
323 bool operator!=(const LockData &other) const {
324 return !(*this == other);
325 }
326
327 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000328 ID.AddInteger(AcquireLoc.getRawEncoding());
329 ID.AddInteger(LKind);
330 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000331};
332
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000333
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000334/// A Lockset maps each MutexID (defined above) to information about how it has
335/// been locked.
336typedef llvm::ImmutableMap<MutexID, LockData> Lockset;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000337typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000338
339class LocalVariableMap;
340
Richard Smith2e515622012-02-03 04:45:26 +0000341/// A side (entry or exit) of a CFG node.
342enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000343
344/// CFGBlockInfo is a struct which contains all the information that is
345/// maintained for each block in the CFG. See LocalVariableMap for more
346/// information about the contexts.
347struct CFGBlockInfo {
348 Lockset EntrySet; // Lockset held at entry to block
349 Lockset ExitSet; // Lockset held at exit from block
350 LocalVarContext EntryContext; // Context held at entry to block
351 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith2e515622012-02-03 04:45:26 +0000352 SourceLocation EntryLoc; // Location of first statement in block
353 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000354 unsigned EntryIndex; // Used to replay contexts later
355
Richard Smith2e515622012-02-03 04:45:26 +0000356 const Lockset &getSet(CFGBlockSide Side) const {
357 return Side == CBS_Entry ? EntrySet : ExitSet;
358 }
359 SourceLocation getLocation(CFGBlockSide Side) const {
360 return Side == CBS_Entry ? EntryLoc : ExitLoc;
361 }
362
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000363private:
364 CFGBlockInfo(Lockset EmptySet, LocalVarContext EmptyCtx)
365 : EntrySet(EmptySet), ExitSet(EmptySet),
366 EntryContext(EmptyCtx), ExitContext(EmptyCtx)
367 { }
368
369public:
370 static CFGBlockInfo getEmptyBlockInfo(Lockset::Factory &F,
371 LocalVariableMap &M);
372};
373
374
375
376// A LocalVariableMap maintains a map from local variables to their currently
377// valid definitions. It provides SSA-like functionality when traversing the
378// CFG. Like SSA, each definition or assignment to a variable is assigned a
379// unique name (an integer), which acts as the SSA name for that definition.
380// The total set of names is shared among all CFG basic blocks.
381// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
382// with their SSA-names. Instead, we compute a Context for each point in the
383// code, which maps local variables to the appropriate SSA-name. This map
384// changes with each assignment.
385//
386// The map is computed in a single pass over the CFG. Subsequent analyses can
387// then query the map to find the appropriate Context for a statement, and use
388// that Context to look up the definitions of variables.
389class LocalVariableMap {
390public:
391 typedef LocalVarContext Context;
392
393 /// A VarDefinition consists of an expression, representing the value of the
394 /// variable, along with the context in which that expression should be
395 /// interpreted. A reference VarDefinition does not itself contain this
396 /// information, but instead contains a pointer to a previous VarDefinition.
397 struct VarDefinition {
398 public:
399 friend class LocalVariableMap;
400
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000401 const NamedDecl *Dec; // The original declaration for this variable.
402 const Expr *Exp; // The expression for this variable, OR
403 unsigned Ref; // Reference to another VarDefinition
404 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000405
406 bool isReference() { return !Exp; }
407
408 private:
409 // Create ordinary variable definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000410 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000411 : Dec(D), Exp(E), Ref(0), Ctx(C)
412 { }
413
414 // Create reference to previous definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000415 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000416 : Dec(D), Exp(0), Ref(R), Ctx(C)
417 { }
418 };
419
420private:
421 Context::Factory ContextFactory;
422 std::vector<VarDefinition> VarDefinitions;
423 std::vector<unsigned> CtxIndices;
424 std::vector<std::pair<Stmt*, Context> > SavedContexts;
425
426public:
427 LocalVariableMap() {
428 // index 0 is a placeholder for undefined variables (aka phi-nodes).
429 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
430 }
431
432 /// Look up a definition, within the given context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000433 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000434 const unsigned *i = Ctx.lookup(D);
435 if (!i)
436 return 0;
437 assert(*i < VarDefinitions.size());
438 return &VarDefinitions[*i];
439 }
440
441 /// Look up the definition for D within the given context. Returns
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000442 /// NULL if the expression is not statically known. If successful, also
443 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000444 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000445 const unsigned *P = Ctx.lookup(D);
446 if (!P)
447 return 0;
448
449 unsigned i = *P;
450 while (i > 0) {
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000451 if (VarDefinitions[i].Exp) {
452 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000453 return VarDefinitions[i].Exp;
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000454 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000455 i = VarDefinitions[i].Ref;
456 }
457 return 0;
458 }
459
460 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
461
462 /// Return the next context after processing S. This function is used by
463 /// clients of the class to get the appropriate context when traversing the
464 /// CFG. It must be called for every assignment or DeclStmt.
465 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
466 if (SavedContexts[CtxIndex+1].first == S) {
467 CtxIndex++;
468 Context Result = SavedContexts[CtxIndex].second;
469 return Result;
470 }
471 return C;
472 }
473
474 void dumpVarDefinitionName(unsigned i) {
475 if (i == 0) {
476 llvm::errs() << "Undefined";
477 return;
478 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000479 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000480 if (!Dec) {
481 llvm::errs() << "<<NULL>>";
482 return;
483 }
484 Dec->printName(llvm::errs());
485 llvm::errs() << "." << i << " " << ((void*) Dec);
486 }
487
488 /// Dumps an ASCII representation of the variable map to llvm::errs()
489 void dump() {
490 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000491 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000492 unsigned Ref = VarDefinitions[i].Ref;
493
494 dumpVarDefinitionName(i);
495 llvm::errs() << " = ";
496 if (Exp) Exp->dump();
497 else {
498 dumpVarDefinitionName(Ref);
499 llvm::errs() << "\n";
500 }
501 }
502 }
503
504 /// Dumps an ASCII representation of a Context to llvm::errs()
505 void dumpContext(Context C) {
506 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000507 const NamedDecl *D = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000508 D->printName(llvm::errs());
509 const unsigned *i = C.lookup(D);
510 llvm::errs() << " -> ";
511 dumpVarDefinitionName(*i);
512 llvm::errs() << "\n";
513 }
514 }
515
516 /// Builds the variable map.
517 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
518 std::vector<CFGBlockInfo> &BlockInfo);
519
520protected:
521 // Get the current context index
522 unsigned getContextIndex() { return SavedContexts.size()-1; }
523
524 // Save the current context for later replay
525 void saveContext(Stmt *S, Context C) {
526 SavedContexts.push_back(std::make_pair(S,C));
527 }
528
529 // Adds a new definition to the given context, and returns a new context.
530 // This method should be called when declaring a new variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000531 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000532 assert(!Ctx.contains(D));
533 unsigned newID = VarDefinitions.size();
534 Context NewCtx = ContextFactory.add(Ctx, D, newID);
535 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
536 return NewCtx;
537 }
538
539 // Add a new reference to an existing definition.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000540 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000541 unsigned newID = VarDefinitions.size();
542 Context NewCtx = ContextFactory.add(Ctx, D, newID);
543 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
544 return NewCtx;
545 }
546
547 // Updates a definition only if that definition is already in the map.
548 // This method should be called when assigning to an existing variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000549 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000550 if (Ctx.contains(D)) {
551 unsigned newID = VarDefinitions.size();
552 Context NewCtx = ContextFactory.remove(Ctx, D);
553 NewCtx = ContextFactory.add(NewCtx, D, newID);
554 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
555 return NewCtx;
556 }
557 return Ctx;
558 }
559
560 // Removes a definition from the context, but keeps the variable name
561 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000562 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000563 Context NewCtx = Ctx;
564 if (NewCtx.contains(D)) {
565 NewCtx = ContextFactory.remove(NewCtx, D);
566 NewCtx = ContextFactory.add(NewCtx, D, 0);
567 }
568 return NewCtx;
569 }
570
571 // Remove a definition entirely frmo the context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000572 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000573 Context NewCtx = Ctx;
574 if (NewCtx.contains(D)) {
575 NewCtx = ContextFactory.remove(NewCtx, D);
576 }
577 return NewCtx;
578 }
579
580 Context intersectContexts(Context C1, Context C2);
581 Context createReferenceContext(Context C);
582 void intersectBackEdge(Context C1, Context C2);
583
584 friend class VarMapBuilder;
585};
586
587
588// This has to be defined after LocalVariableMap.
589CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(Lockset::Factory &F,
590 LocalVariableMap &M) {
591 return CFGBlockInfo(F.getEmptyMap(), M.getEmptyContext());
592}
593
594
595/// Visitor which builds a LocalVariableMap
596class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
597public:
598 LocalVariableMap* VMap;
599 LocalVariableMap::Context Ctx;
600
601 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
602 : VMap(VM), Ctx(C) {}
603
604 void VisitDeclStmt(DeclStmt *S);
605 void VisitBinaryOperator(BinaryOperator *BO);
606};
607
608
609// Add new local variables to the variable map
610void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
611 bool modifiedCtx = false;
612 DeclGroupRef DGrp = S->getDeclGroup();
613 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
614 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
615 Expr *E = VD->getInit();
616
617 // Add local variables with trivial type to the variable map
618 QualType T = VD->getType();
619 if (T.isTrivialType(VD->getASTContext())) {
620 Ctx = VMap->addDefinition(VD, E, Ctx);
621 modifiedCtx = true;
622 }
623 }
624 }
625 if (modifiedCtx)
626 VMap->saveContext(S, Ctx);
627}
628
629// Update local variable definitions in variable map
630void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
631 if (!BO->isAssignmentOp())
632 return;
633
634 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
635
636 // Update the variable map and current context.
637 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
638 ValueDecl *VDec = DRE->getDecl();
639 if (Ctx.lookup(VDec)) {
640 if (BO->getOpcode() == BO_Assign)
641 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
642 else
643 // FIXME -- handle compound assignment operators
644 Ctx = VMap->clearDefinition(VDec, Ctx);
645 VMap->saveContext(BO, Ctx);
646 }
647 }
648}
649
650
651// Computes the intersection of two contexts. The intersection is the
652// set of variables which have the same definition in both contexts;
653// variables with different definitions are discarded.
654LocalVariableMap::Context
655LocalVariableMap::intersectContexts(Context C1, Context C2) {
656 Context Result = C1;
657 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000658 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000659 unsigned i1 = I.getData();
660 const unsigned *i2 = C2.lookup(Dec);
661 if (!i2) // variable doesn't exist on second path
662 Result = removeDefinition(Dec, Result);
663 else if (*i2 != i1) // variable exists, but has different definition
664 Result = clearDefinition(Dec, Result);
665 }
666 return Result;
667}
668
669// For every variable in C, create a new variable that refers to the
670// definition in C. Return a new context that contains these new variables.
671// (We use this for a naive implementation of SSA on loop back-edges.)
672LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
673 Context Result = getEmptyContext();
674 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000675 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000676 unsigned i = I.getData();
677 Result = addReference(Dec, i, Result);
678 }
679 return Result;
680}
681
682// This routine also takes the intersection of C1 and C2, but it does so by
683// altering the VarDefinitions. C1 must be the result of an earlier call to
684// createReferenceContext.
685void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
686 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000687 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000688 unsigned i1 = I.getData();
689 VarDefinition *VDef = &VarDefinitions[i1];
690 assert(VDef->isReference());
691
692 const unsigned *i2 = C2.lookup(Dec);
693 if (!i2 || (*i2 != i1))
694 VDef->Ref = 0; // Mark this variable as undefined
695 }
696}
697
698
699// Traverse the CFG in topological order, so all predecessors of a block
700// (excluding back-edges) are visited before the block itself. At
701// each point in the code, we calculate a Context, which holds the set of
702// variable definitions which are visible at that point in execution.
703// Visible variables are mapped to their definitions using an array that
704// contains all definitions.
705//
706// At join points in the CFG, the set is computed as the intersection of
707// the incoming sets along each edge, E.g.
708//
709// { Context | VarDefinitions }
710// int x = 0; { x -> x1 | x1 = 0 }
711// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
712// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
713// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
714// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
715//
716// This is essentially a simpler and more naive version of the standard SSA
717// algorithm. Those definitions that remain in the intersection are from blocks
718// that strictly dominate the current block. We do not bother to insert proper
719// phi nodes, because they are not used in our analysis; instead, wherever
720// a phi node would be required, we simply remove that definition from the
721// context (E.g. x above).
722//
723// The initial traversal does not capture back-edges, so those need to be
724// handled on a separate pass. Whenever the first pass encounters an
725// incoming back edge, it duplicates the context, creating new definitions
726// that refer back to the originals. (These correspond to places where SSA
727// might have to insert a phi node.) On the second pass, these definitions are
728// set to NULL if the the variable has changed on the back-edge (i.e. a phi
729// node was actually required.) E.g.
730//
731// { Context | VarDefinitions }
732// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
733// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
734// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
735// ... { y -> y1 | x3 = 2, x2 = 1, ... }
736//
737void LocalVariableMap::traverseCFG(CFG *CFGraph,
738 PostOrderCFGView *SortedGraph,
739 std::vector<CFGBlockInfo> &BlockInfo) {
740 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
741
742 CtxIndices.resize(CFGraph->getNumBlockIDs());
743
744 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
745 E = SortedGraph->end(); I!= E; ++I) {
746 const CFGBlock *CurrBlock = *I;
747 int CurrBlockID = CurrBlock->getBlockID();
748 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
749
750 VisitedBlocks.insert(CurrBlock);
751
752 // Calculate the entry context for the current block
753 bool HasBackEdges = false;
754 bool CtxInit = true;
755 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
756 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
757 // if *PI -> CurrBlock is a back edge, so skip it
758 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
759 HasBackEdges = true;
760 continue;
761 }
762
763 int PrevBlockID = (*PI)->getBlockID();
764 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
765
766 if (CtxInit) {
767 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
768 CtxInit = false;
769 }
770 else {
771 CurrBlockInfo->EntryContext =
772 intersectContexts(CurrBlockInfo->EntryContext,
773 PrevBlockInfo->ExitContext);
774 }
775 }
776
777 // Duplicate the context if we have back-edges, so we can call
778 // intersectBackEdges later.
779 if (HasBackEdges)
780 CurrBlockInfo->EntryContext =
781 createReferenceContext(CurrBlockInfo->EntryContext);
782
783 // Create a starting context index for the current block
784 saveContext(0, CurrBlockInfo->EntryContext);
785 CurrBlockInfo->EntryIndex = getContextIndex();
786
787 // Visit all the statements in the basic block.
788 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
789 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
790 BE = CurrBlock->end(); BI != BE; ++BI) {
791 switch (BI->getKind()) {
792 case CFGElement::Statement: {
793 const CFGStmt *CS = cast<CFGStmt>(&*BI);
794 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
795 break;
796 }
797 default:
798 break;
799 }
800 }
801 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
802
803 // Mark variables on back edges as "unknown" if they've been changed.
804 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
805 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
806 // if CurrBlock -> *SI is *not* a back edge
807 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
808 continue;
809
810 CFGBlock *FirstLoopBlock = *SI;
811 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
812 Context LoopEnd = CurrBlockInfo->ExitContext;
813 intersectBackEdge(LoopBegin, LoopEnd);
814 }
815 }
816
817 // Put an extra entry at the end of the indexed context array
818 unsigned exitID = CFGraph->getExit().getBlockID();
819 saveContext(0, BlockInfo[exitID].ExitContext);
820}
821
Richard Smith2e515622012-02-03 04:45:26 +0000822/// Find the appropriate source locations to use when producing diagnostics for
823/// each block in the CFG.
824static void findBlockLocations(CFG *CFGraph,
825 PostOrderCFGView *SortedGraph,
826 std::vector<CFGBlockInfo> &BlockInfo) {
827 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
828 E = SortedGraph->end(); I!= E; ++I) {
829 const CFGBlock *CurrBlock = *I;
830 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
831
832 // Find the source location of the last statement in the block, if the
833 // block is not empty.
834 if (const Stmt *S = CurrBlock->getTerminator()) {
835 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
836 } else {
837 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
838 BE = CurrBlock->rend(); BI != BE; ++BI) {
839 // FIXME: Handle other CFGElement kinds.
840 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
841 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
842 break;
843 }
844 }
845 }
846
847 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
848 // This block contains at least one statement. Find the source location
849 // of the first statement in the block.
850 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
851 BE = CurrBlock->end(); BI != BE; ++BI) {
852 // FIXME: Handle other CFGElement kinds.
853 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
854 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
855 break;
856 }
857 }
858 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
859 CurrBlock != &CFGraph->getExit()) {
860 // The block is empty, and has a single predecessor. Use its exit
861 // location.
862 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
863 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
864 }
865 }
866}
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000867
868/// \brief Class which implements the core thread safety analysis routines.
869class ThreadSafetyAnalyzer {
870 friend class BuildLockset;
871
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000872 ThreadSafetyHandler &Handler;
873 Lockset::Factory LocksetFactory;
874 LocalVariableMap LocalVarMap;
875 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000876
877public:
878 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
879
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000880 Lockset addLock(const Lockset &LSet, const MutexID &Mutex,
881 const LockData &LDat);
882 Lockset addLock(const Lockset &LSet, Expr *MutexExp, const NamedDecl *D,
883 const LockData &LDat);
884 Lockset removeLock(const Lockset &LSet, const MutexID &Mutex,
885 SourceLocation UnlockLoc);
886
887 template <class AttrType>
888 Lockset addLocksToSet(const Lockset &LSet, LockKind LK, AttrType *Attr,
889 Expr *Exp, NamedDecl *D, VarDecl *VD = 0);
890 Lockset removeLocksFromSet(const Lockset &LSet,
891 UnlockFunctionAttr *Attr,
892 Expr *Exp, NamedDecl* FunDecl);
893
894 template <class AttrType>
895 Lockset addTrylock(const Lockset &LSet,
896 LockKind LK, AttrType *Attr, Expr *Exp, NamedDecl *FunDecl,
897 const CFGBlock* PredBlock, const CFGBlock *CurrBlock,
898 Expr *BrE, bool Neg);
899 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
900 bool &Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000901
DeLesley Hutchins0da44142012-06-22 17:07:28 +0000902 Lockset getEdgeLockset(const Lockset &ExitSet,
903 const CFGBlock* PredBlock,
904 const CFGBlock *CurrBlock);
905
906 Lockset intersectAndWarn(const Lockset &LSet1, const Lockset &LSet2,
907 SourceLocation JoinLoc, LockErrorKind LEK);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000908
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000909 void runAnalysis(AnalysisDeclContext &AC);
910};
911
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000912
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000913/// \brief Add a new lock to the lockset, warning if the lock is already there.
914/// \param Mutex -- the Mutex expression for the lock
915/// \param LDat -- the LockData for the lock
916Lockset ThreadSafetyAnalyzer::addLock(const Lockset &LSet,
917 const MutexID &Mutex,
918 const LockData &LDat) {
919 // FIXME: deal with acquired before/after annotations.
920 // FIXME: Don't always warn when we have support for reentrant locks.
921 if (LSet.lookup(Mutex)) {
922 Handler.handleDoubleLock(Mutex.getName(), LDat.AcquireLoc);
923 return LSet;
924 } else {
925 return LocksetFactory.add(LSet, Mutex, LDat);
926 }
927}
928
929/// \brief Construct a new mutex and add it to the lockset.
930Lockset ThreadSafetyAnalyzer::addLock(const Lockset &LSet,
931 Expr *MutexExp, const NamedDecl *D,
932 const LockData &LDat) {
933 MutexID Mutex(MutexExp, 0, D);
934 if (!Mutex.isValid()) {
935 MutexID::warnInvalidLock(Handler, MutexExp, 0, D);
936 return LSet;
937 }
938 return addLock(LSet, Mutex, LDat);
939}
940
941
942/// \brief Remove a lock from the lockset, warning if the lock is not there.
943/// \param LockExp The lock expression corresponding to the lock to be removed
944/// \param UnlockLoc The source location of the unlock (only used in error msg)
945Lockset ThreadSafetyAnalyzer::removeLock(const Lockset &LSet,
946 const MutexID &Mutex,
947 SourceLocation UnlockLoc) {
948 const LockData *LDat = LSet.lookup(Mutex);
949 if (!LDat) {
950 Handler.handleUnmatchedUnlock(Mutex.getName(), UnlockLoc);
951 return LSet;
952 }
953 else {
954 Lockset Result = LSet;
955 // For scoped-lockable vars, remove the mutex associated with this var.
956 if (LDat->UnderlyingMutex.isValid())
957 Result = removeLock(Result, LDat->UnderlyingMutex, UnlockLoc);
958 return LocksetFactory.remove(Result, Mutex);
959 }
960}
961
962/// \brief This function, parameterized by an attribute type, is used to add a
963/// set of locks specified as attribute arguments to the lockset.
964template <typename AttrType>
965Lockset ThreadSafetyAnalyzer::addLocksToSet(const Lockset &LSet,
966 LockKind LK, AttrType *Attr,
967 Expr *Exp, NamedDecl* FunDecl,
968 VarDecl *VD) {
969 typedef typename AttrType::args_iterator iterator_type;
970
971 SourceLocation ExpLocation = Exp->getExprLoc();
972
973 // Figure out if we're calling the constructor of scoped lockable class
974 bool isScopedVar = false;
975 if (VD) {
976 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FunDecl)) {
977 CXXRecordDecl* PD = CD->getParent();
978 if (PD && PD->getAttr<ScopedLockableAttr>())
979 isScopedVar = true;
980 }
981 }
982
983 if (Attr->args_size() == 0) {
984 // The mutex held is the "this" object.
985 MutexID Mutex(0, Exp, FunDecl);
986 if (!Mutex.isValid()) {
987 MutexID::warnInvalidLock(Handler, 0, Exp, FunDecl);
988 return LSet;
989 }
990 else {
991 return addLock(LSet, Mutex, LockData(ExpLocation, LK));
992 }
993 }
994
995 Lockset Result = LSet;
996 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
997 MutexID Mutex(*I, Exp, FunDecl);
998 if (!Mutex.isValid())
999 MutexID::warnInvalidLock(Handler, *I, Exp, FunDecl);
1000 else {
1001 Result = addLock(Result, Mutex, LockData(ExpLocation, LK));
1002 if (isScopedVar) {
1003 // For scoped lockable vars, map this var to its underlying mutex.
1004 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
1005 MutexID SMutex(&DRE, 0, 0);
1006 Result = addLock(Result, SMutex,
1007 LockData(VD->getLocation(), LK, Mutex));
1008 }
1009 }
1010 }
1011 return Result;
1012}
1013
1014/// \brief This function removes a set of locks specified as attribute
1015/// arguments from the lockset.
1016Lockset ThreadSafetyAnalyzer::removeLocksFromSet(const Lockset &LSet,
1017 UnlockFunctionAttr *Attr,
1018 Expr *Exp, NamedDecl* FunDecl) {
1019 SourceLocation ExpLocation;
1020 if (Exp) ExpLocation = Exp->getExprLoc();
1021
1022 if (Attr->args_size() == 0) {
1023 // The mutex held is the "this" object.
1024 MutexID Mu(0, Exp, FunDecl);
1025 if (!Mu.isValid()) {
1026 MutexID::warnInvalidLock(Handler, 0, Exp, FunDecl);
1027 return LSet;
1028 } else {
1029 return removeLock(LSet, Mu, ExpLocation);
1030 }
1031 }
1032
1033 Lockset Result = LSet;
1034 for (UnlockFunctionAttr::args_iterator I = Attr->args_begin(),
1035 E = Attr->args_end(); I != E; ++I) {
1036 MutexID Mutex(*I, Exp, FunDecl);
1037 if (!Mutex.isValid())
1038 MutexID::warnInvalidLock(Handler, *I, Exp, FunDecl);
1039 else
1040 Result = removeLock(Result, Mutex, ExpLocation);
1041 }
1042 return Result;
1043}
1044
1045
1046/// \brief Add lock to set, if the current block is in the taken branch of a
1047/// trylock.
1048template <class AttrType>
1049Lockset ThreadSafetyAnalyzer::addTrylock(const Lockset &LSet,
1050 LockKind LK, AttrType *Attr,
1051 Expr *Exp, NamedDecl *FunDecl,
1052 const CFGBlock *PredBlock,
1053 const CFGBlock *CurrBlock,
1054 Expr *BrE, bool Neg) {
1055 // Find out which branch has the lock
1056 bool branch = 0;
1057 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1058 branch = BLE->getValue();
1059 }
1060 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1061 branch = ILE->getValue().getBoolValue();
1062 }
1063 int branchnum = branch ? 0 : 1;
1064 if (Neg) branchnum = !branchnum;
1065
1066 Lockset Result = LSet;
1067 // If we've taken the trylock branch, then add the lock
1068 int i = 0;
1069 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1070 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1071 if (*SI == CurrBlock && i == branchnum) {
1072 Result = addLocksToSet(Result, LK, Attr, Exp, FunDecl, 0);
1073 }
1074 }
1075 return Result;
1076}
1077
1078
1079// If Cond can be traced back to a function call, return the call expression.
1080// The negate variable should be called with false, and will be set to true
1081// if the function call is negated, e.g. if (!mu.tryLock(...))
1082const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1083 LocalVarContext C,
1084 bool &Negate) {
1085 if (!Cond)
1086 return 0;
1087
1088 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1089 return CallExp;
1090 }
1091 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1092 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1093 }
1094 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1095 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1096 return getTrylockCallExpr(E, C, Negate);
1097 }
1098 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1099 if (UOP->getOpcode() == UO_LNot) {
1100 Negate = !Negate;
1101 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1102 }
1103 }
1104 // FIXME -- handle && and || as well.
1105 return NULL;
1106}
1107
1108
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001109/// \brief Find the lockset that holds on the edge between PredBlock
1110/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1111/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1112Lockset ThreadSafetyAnalyzer::getEdgeLockset(const Lockset &ExitSet,
1113 const CFGBlock *PredBlock,
1114 const CFGBlock *CurrBlock) {
1115 if (!PredBlock->getTerminatorCondition())
1116 return ExitSet;
1117
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001118 bool Negate = false;
1119 const Stmt *Cond = PredBlock->getTerminatorCondition();
1120 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1121 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1122
1123 CallExpr *Exp = const_cast<CallExpr*>(
1124 getTrylockCallExpr(Cond, LVarCtx, Negate));
1125 if (!Exp)
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001126 return ExitSet;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001127
1128 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1129 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001130 return ExitSet;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001131
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001132 Lockset Result = ExitSet;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001133
1134 // If the condition is a call to a Trylock function, then grab the attributes
1135 AttrVec &ArgAttrs = FunDecl->getAttrs();
1136 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1137 Attr *Attr = ArgAttrs[i];
1138 switch (Attr->getKind()) {
1139 case attr::ExclusiveTrylockFunction: {
1140 ExclusiveTrylockFunctionAttr *A =
1141 cast<ExclusiveTrylockFunctionAttr>(Attr);
1142 Result = addTrylock(Result, LK_Exclusive, A, Exp, FunDecl,
1143 PredBlock, CurrBlock,
1144 A->getSuccessValue(), Negate);
1145 break;
1146 }
1147 case attr::SharedTrylockFunction: {
1148 SharedTrylockFunctionAttr *A =
1149 cast<SharedTrylockFunctionAttr>(Attr);
1150 Result = addTrylock(Result, LK_Shared, A, Exp, FunDecl,
1151 PredBlock, CurrBlock,
1152 A->getSuccessValue(), Negate);
1153 break;
1154 }
1155 default:
1156 break;
1157 }
1158 }
1159 return Result;
1160}
1161
1162
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001163/// \brief We use this class to visit different types of expressions in
1164/// CFGBlocks, and build up the lockset.
1165/// An expression may cause us to add or remove locks from the lockset, or else
1166/// output error messages related to missing locks.
1167/// FIXME: In future, we may be able to not inherit from a visitor.
1168class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001169 friend class ThreadSafetyAnalyzer;
1170
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001171 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001172 Lockset LSet;
1173 LocalVariableMap::Context LVarCtx;
1174 unsigned CtxIndex;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001175
1176 // Helper functions
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001177 const ValueDecl *getValueDecl(Expr *Exp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001178
1179 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1180 Expr *MutexExp, ProtectedOperationKind POK);
1181
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001182 void checkAccess(Expr *Exp, AccessKind AK);
1183 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001184 void handleCall(Expr *Exp, NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001185
1186 /// \brief Returns true if the lockset contains a lock, regardless of whether
1187 /// the lock is held exclusively or shared.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001188 bool locksetContains(const MutexID &Lock) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001189 return LSet.lookup(Lock);
1190 }
1191
1192 /// \brief Returns true if the lockset contains a lock with the passed in
1193 /// locktype.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001194 bool locksetContains(const MutexID &Lock, LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001195 const LockData *LockHeld = LSet.lookup(Lock);
1196 return (LockHeld && KindRequested == LockHeld->LKind);
1197 }
1198
1199 /// \brief Returns true if the lockset contains a lock with at least the
1200 /// passed in locktype. So for example, if we pass in LK_Shared, this function
1201 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
1202 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001203 bool locksetContainsAtLeast(const MutexID &Lock,
1204 LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001205 switch (KindRequested) {
1206 case LK_Shared:
1207 return locksetContains(Lock);
1208 case LK_Exclusive:
1209 return locksetContains(Lock, KindRequested);
1210 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00001211 llvm_unreachable("Unknown LockKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001212 }
1213
1214public:
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001215 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001216 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001217 Analyzer(Anlzr),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001218 LSet(Info.EntrySet),
1219 LVarCtx(Info.EntryContext),
1220 CtxIndex(Info.EntryIndex)
1221 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001222
1223 void VisitUnaryOperator(UnaryOperator *UO);
1224 void VisitBinaryOperator(BinaryOperator *BO);
1225 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001226 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001227 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001228 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001229};
1230
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001231
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001232/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1233const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1234 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1235 return DR->getDecl();
1236
1237 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1238 return ME->getMemberDecl();
1239
1240 return 0;
1241}
1242
1243/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001244/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001245void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1246 AccessKind AK, Expr *MutexExp,
1247 ProtectedOperationKind POK) {
1248 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001249
1250 MutexID Mutex(MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001251 if (!Mutex.isValid())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001252 MutexID::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001253 else if (!locksetContainsAtLeast(Mutex, LK))
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001254 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.getName(), LK,
1255 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001256}
1257
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001258/// \brief This method identifies variable dereferences and checks pt_guarded_by
1259/// and pt_guarded_var annotations. Note that we only check these annotations
1260/// at the time a pointer is dereferenced.
1261/// FIXME: We need to check for other types of pointer dereferences
1262/// (e.g. [], ->) and deal with them here.
1263/// \param Exp An expression that has been read or written.
1264void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1265 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1266 if (!UO || UO->getOpcode() != clang::UO_Deref)
1267 return;
1268 Exp = UO->getSubExpr()->IgnoreParenCasts();
1269
1270 const ValueDecl *D = getValueDecl(Exp);
1271 if(!D || !D->hasAttrs())
1272 return;
1273
1274 if (D->getAttr<PtGuardedVarAttr>() && LSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001275 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1276 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001277
1278 const AttrVec &ArgAttrs = D->getAttrs();
1279 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1280 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1281 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1282}
1283
1284/// \brief Checks guarded_by and guarded_var attributes.
1285/// Whenever we identify an access (read or write) of a DeclRefExpr or
1286/// MemberExpr, we need to check whether there are any guarded_by or
1287/// guarded_var attributes, and make sure we hold the appropriate mutexes.
1288void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1289 const ValueDecl *D = getValueDecl(Exp);
1290 if(!D || !D->hasAttrs())
1291 return;
1292
1293 if (D->getAttr<GuardedVarAttr>() && LSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001294 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1295 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001296
1297 const AttrVec &ArgAttrs = D->getAttrs();
1298 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1299 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1300 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1301}
1302
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001303/// \brief Process a function call, method call, constructor call,
1304/// or destructor call. This involves looking at the attributes on the
1305/// corresponding function/method/constructor/destructor, issuing warnings,
1306/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001307///
1308/// FIXME: For classes annotated with one of the guarded annotations, we need
1309/// to treat const method calls as reads and non-const method calls as writes,
1310/// and check that the appropriate locks are held. Non-const method calls with
1311/// the same signature as const method calls can be also treated as reads.
1312///
1313/// FIXME: We need to also visit CallExprs to catch/check global functions.
Caitlin Sadowski1748b122011-09-16 00:35:54 +00001314///
1315/// FIXME: Do not flag an error for member variables accessed in constructors/
1316/// destructors
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001317void BuildLockset::handleCall(Expr *Exp, NamedDecl *D, VarDecl *VD) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001318 AttrVec &ArgAttrs = D->getAttrs();
1319 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
1320 Attr *Attr = ArgAttrs[i];
1321 switch (Attr->getKind()) {
1322 // When we encounter an exclusive lock function, we need to add the lock
1323 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001324 case attr::ExclusiveLockFunction: {
1325 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(Attr);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001326 LSet = Analyzer->addLocksToSet(LSet, LK_Exclusive, A, Exp, D, VD);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001327 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001328 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001329
1330 // When we encounter a shared lock function, we need to add the lock
1331 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001332 case attr::SharedLockFunction: {
1333 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(Attr);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001334 LSet = Analyzer->addLocksToSet(LSet, LK_Shared, A, Exp, D, VD);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001335 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001336 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001337
1338 // When we encounter an unlock function, we need to remove unlocked
1339 // mutexes from the lockset, and flag a warning if they are not there.
1340 case attr::UnlockFunction: {
1341 UnlockFunctionAttr *UFAttr = cast<UnlockFunctionAttr>(Attr);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001342 LSet = Analyzer->removeLocksFromSet(LSet, UFAttr, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001343 break;
1344 }
1345
1346 case attr::ExclusiveLocksRequired: {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001347 ExclusiveLocksRequiredAttr *ELRAttr =
1348 cast<ExclusiveLocksRequiredAttr>(Attr);
1349
1350 for (ExclusiveLocksRequiredAttr::args_iterator
1351 I = ELRAttr->args_begin(), E = ELRAttr->args_end(); I != E; ++I)
1352 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1353 break;
1354 }
1355
1356 case attr::SharedLocksRequired: {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001357 SharedLocksRequiredAttr *SLRAttr = cast<SharedLocksRequiredAttr>(Attr);
1358
1359 for (SharedLocksRequiredAttr::args_iterator I = SLRAttr->args_begin(),
1360 E = SLRAttr->args_end(); I != E; ++I)
1361 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1362 break;
1363 }
1364
1365 case attr::LocksExcluded: {
1366 LocksExcludedAttr *LEAttr = cast<LocksExcludedAttr>(Attr);
1367 for (LocksExcludedAttr::args_iterator I = LEAttr->args_begin(),
1368 E = LEAttr->args_end(); I != E; ++I) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001369 MutexID Mutex(*I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001370 if (!Mutex.isValid())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001371 MutexID::warnInvalidLock(Analyzer->Handler, *I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001372 else if (locksetContains(Mutex))
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001373 Analyzer->Handler.handleFunExcludesLock(D->getName(),
1374 Mutex.getName(),
1375 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001376 }
1377 break;
1378 }
1379
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001380 // Ignore other (non thread-safety) attributes
1381 default:
1382 break;
1383 }
1384 }
1385}
1386
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +00001387
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001388/// \brief For unary operations which read and write a variable, we need to
1389/// check whether we hold any required mutexes. Reads are checked in
1390/// VisitCastExpr.
1391void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1392 switch (UO->getOpcode()) {
1393 case clang::UO_PostDec:
1394 case clang::UO_PostInc:
1395 case clang::UO_PreDec:
1396 case clang::UO_PreInc: {
1397 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1398 checkAccess(SubExp, AK_Written);
1399 checkDereference(SubExp, AK_Written);
1400 break;
1401 }
1402 default:
1403 break;
1404 }
1405}
1406
1407/// For binary operations which assign to a variable (writes), we need to check
1408/// whether we hold any required mutexes.
1409/// FIXME: Deal with non-primitive types.
1410void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1411 if (!BO->isAssignmentOp())
1412 return;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001413
1414 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001415 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001416
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001417 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1418 checkAccess(LHSExp, AK_Written);
1419 checkDereference(LHSExp, AK_Written);
1420}
1421
1422/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1423/// need to ensure we hold any required mutexes.
1424/// FIXME: Deal with non-primitive types.
1425void BuildLockset::VisitCastExpr(CastExpr *CE) {
1426 if (CE->getCastKind() != CK_LValueToRValue)
1427 return;
1428 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
1429 checkAccess(SubExp, AK_Read);
1430 checkDereference(SubExp, AK_Read);
1431}
1432
1433
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001434void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001435 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1436 if(!D || !D->hasAttrs())
1437 return;
1438 handleCall(Exp, D);
1439}
1440
1441void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001442 // FIXME -- only handles constructors in DeclStmt below.
1443}
1444
1445void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001446 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001447 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001448
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001449 DeclGroupRef DGrp = S->getDeclGroup();
1450 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1451 Decl *D = *I;
1452 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1453 Expr *E = VD->getInit();
1454 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1455 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1456 if (!CtorD || !CtorD->hasAttrs())
1457 return;
1458 handleCall(CE, CtorD, VD);
1459 }
1460 }
1461 }
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001462}
1463
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001464
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001465
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001466/// \brief Compute the intersection of two locksets and issue warnings for any
1467/// locks in the symmetric difference.
1468///
1469/// This function is used at a merge point in the CFG when comparing the lockset
1470/// of each branch being merged. For example, given the following sequence:
1471/// A; if () then B; else C; D; we need to check that the lockset after B and C
1472/// are the same. In the event of a difference, we use the intersection of these
1473/// two locksets at the start of D.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001474///
1475/// \param LSet1 The first lockset.
1476/// \param LSet2 The second lockset.
1477/// \param JoinLoc The location of the join point for error reporting
1478/// \param LEK The error message to report.
1479Lockset ThreadSafetyAnalyzer::intersectAndWarn(const Lockset &LSet1,
1480 const Lockset &LSet2,
1481 SourceLocation JoinLoc,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001482 LockErrorKind LEK) {
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001483 Lockset Intersection = LSet1;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001484
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001485 for (Lockset::iterator I = LSet2.begin(), E = LSet2.end(); I != E; ++I) {
1486 const MutexID &LSet2Mutex = I.getKey();
1487 const LockData &LSet2LockData = I.getData();
1488 if (const LockData *LD = LSet1.lookup(LSet2Mutex)) {
1489 if (LD->LKind != LSet2LockData.LKind) {
1490 Handler.handleExclusiveAndShared(LSet2Mutex.getName(),
1491 LSet2LockData.AcquireLoc,
1492 LD->AcquireLoc);
1493 if (LD->LKind != LK_Exclusive)
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001494 Intersection = LocksetFactory.add(Intersection, LSet2Mutex,
1495 LSet2LockData);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001496 }
1497 } else {
1498 Handler.handleMutexHeldEndOfScope(LSet2Mutex.getName(),
Richard Smith2e515622012-02-03 04:45:26 +00001499 LSet2LockData.AcquireLoc,
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001500 JoinLoc, LEK);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001501 }
1502 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001503
1504 for (Lockset::iterator I = LSet1.begin(), E = LSet1.end(); I != E; ++I) {
1505 if (!LSet2.contains(I.getKey())) {
1506 const MutexID &Mutex = I.getKey();
1507 const LockData &MissingLock = I.getData();
1508 Handler.handleMutexHeldEndOfScope(Mutex.getName(),
Richard Smith2e515622012-02-03 04:45:26 +00001509 MissingLock.AcquireLoc,
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001510 JoinLoc, LEK);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001511 Intersection = LocksetFactory.remove(Intersection, Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001512 }
1513 }
1514 return Intersection;
1515}
1516
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001517
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001518/// \brief Check a function's CFG for thread-safety violations.
1519///
1520/// We traverse the blocks in the CFG, compute the set of mutexes that are held
1521/// at the end of each block, and issue warnings for thread safety violations.
1522/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00001523void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001524 CFG *CFGraph = AC.getCFG();
1525 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001526 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
1527
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001528 // AC.dumpCFG(true);
1529
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001530 if (!D)
1531 return; // Ignore anonymous functions for now.
1532 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
1533 return;
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001534 // FIXME: Do something a bit more intelligent inside constructor and
1535 // destructor code. Constructors and destructors must assume unique access
1536 // to 'this', so checks on member variable access is disabled, but we should
1537 // still enable checks on other objects.
1538 if (isa<CXXConstructorDecl>(D))
1539 return; // Don't check inside constructors.
1540 if (isa<CXXDestructorDecl>(D))
1541 return; // Don't check inside destructors.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001542
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001543 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001544 CFGBlockInfo::getEmptyBlockInfo(LocksetFactory, LocalVarMap));
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001545
1546 // We need to explore the CFG via a "topological" ordering.
1547 // That way, we will be guaranteed to have information about required
1548 // predecessor locksets when exploring a new block.
Ted Kremenek439ed162011-10-22 02:14:27 +00001549 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
1550 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001551
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001552 // Compute SSA names for local variables
1553 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
1554
Richard Smith2e515622012-02-03 04:45:26 +00001555 // Fill in source locations for all CFGBlocks.
1556 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
1557
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001558 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001559 // to initial lockset. Also turn off checking for lock and unlock functions.
1560 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek439ed162011-10-22 02:14:27 +00001561 if (!SortedGraph->empty() && D->hasAttrs()) {
1562 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001563 Lockset &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001564 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001565 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001566 Attr *Attr = ArgAttrs[i];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00001567 SourceLocation AttrLoc = Attr->getLocation();
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001568 if (SharedLocksRequiredAttr *SLRAttr
1569 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
1570 for (SharedLocksRequiredAttr::args_iterator
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001571 SLRIter = SLRAttr->args_begin(),
1572 SLREnd = SLRAttr->args_end(); SLRIter != SLREnd; ++SLRIter)
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001573 InitialLockset = addLock(InitialLockset, *SLRIter, D,
1574 LockData(AttrLoc, LK_Shared));
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001575 } else if (ExclusiveLocksRequiredAttr *ELRAttr
1576 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
1577 for (ExclusiveLocksRequiredAttr::args_iterator
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001578 ELRIter = ELRAttr->args_begin(),
1579 ELREnd = ELRAttr->args_end(); ELRIter != ELREnd; ++ELRIter)
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001580 InitialLockset = addLock(InitialLockset, *ELRIter, D,
1581 LockData(AttrLoc, LK_Exclusive));
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001582 } else if (isa<UnlockFunctionAttr>(Attr)) {
1583 // Don't try to check unlock functions for now
1584 return;
1585 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
1586 // Don't try to check lock functions for now
1587 return;
1588 } else if (isa<SharedLockFunctionAttr>(Attr)) {
1589 // Don't try to check lock functions for now
1590 return;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001591 }
1592 }
1593 }
1594
Ted Kremenek439ed162011-10-22 02:14:27 +00001595 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1596 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001597 const CFGBlock *CurrBlock = *I;
1598 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001599 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001600
1601 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001602 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001603
1604 // Iterate through the predecessor blocks and warn if the lockset for all
1605 // predecessors is not the same. We take the entry lockset of the current
1606 // block to be the intersection of all previous locksets.
1607 // FIXME: By keeping the intersection, we may output more errors in future
1608 // for a lock which is not in the intersection, but was in the union. We
1609 // may want to also keep the union in future. As an example, let's say
1610 // the intersection contains Mutex L, and the union contains L and M.
1611 // Later we unlock M. At this point, we would output an error because we
1612 // never locked M; although the real error is probably that we forgot to
1613 // lock M on all code paths. Conversely, let's say that later we lock M.
1614 // In this case, we should compare against the intersection instead of the
1615 // union because the real error is probably that we forgot to unlock M on
1616 // all code paths.
1617 bool LocksetInitialized = false;
Richard Smithaacde712012-02-03 03:30:07 +00001618 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001619 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1620 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1621
1622 // if *PI -> CurrBlock is a back edge
1623 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
1624 continue;
1625
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00001626 // Ignore edges from blocks that can't return.
1627 if ((*PI)->hasNoReturnElement())
1628 continue;
1629
Richard Smithaacde712012-02-03 03:30:07 +00001630 // If the previous block ended in a 'continue' or 'break' statement, then
1631 // a difference in locksets is probably due to a bug in that block, rather
1632 // than in some other predecessor. In that case, keep the other
1633 // predecessor's lockset.
1634 if (const Stmt *Terminator = (*PI)->getTerminator()) {
1635 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
1636 SpecialBlocks.push_back(*PI);
1637 continue;
1638 }
1639 }
1640
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001641 int PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001642 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001643 Lockset PrevLockset =
1644 getEdgeLockset(PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001645
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001646 if (!LocksetInitialized) {
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001647 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001648 LocksetInitialized = true;
1649 } else {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001650 CurrBlockInfo->EntrySet =
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001651 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
1652 CurrBlockInfo->EntryLoc,
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001653 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001654 }
1655 }
1656
Richard Smithaacde712012-02-03 03:30:07 +00001657 // Process continue and break blocks. Assume that the lockset for the
1658 // resulting block is unaffected by any discrepancies in them.
1659 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
1660 SpecialI < SpecialN; ++SpecialI) {
1661 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
1662 int PrevBlockID = PrevBlock->getBlockID();
1663 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1664
1665 if (!LocksetInitialized) {
1666 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
1667 LocksetInitialized = true;
1668 } else {
1669 // Determine whether this edge is a loop terminator for diagnostic
1670 // purposes. FIXME: A 'break' statement might be a loop terminator, but
1671 // it might also be part of a switch. Also, a subsequent destructor
1672 // might add to the lockset, in which case the real issue might be a
1673 // double lock on the other path.
1674 const Stmt *Terminator = PrevBlock->getTerminator();
1675 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
1676
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001677 Lockset PrevLockset =
1678 getEdgeLockset(PrevBlockInfo->ExitSet, PrevBlock, CurrBlock);
1679
Richard Smithaacde712012-02-03 03:30:07 +00001680 // Do not update EntrySet.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001681 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
1682 PrevBlockInfo->ExitLoc,
Richard Smithaacde712012-02-03 03:30:07 +00001683 IsLoop ? LEK_LockedSomeLoopIterations
1684 : LEK_LockedSomePredecessors);
1685 }
1686 }
1687
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001688 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
1689
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001690 // Visit all the statements in the basic block.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001691 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1692 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00001693 switch (BI->getKind()) {
1694 case CFGElement::Statement: {
1695 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1696 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1697 break;
1698 }
1699 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
1700 case CFGElement::AutomaticObjectDtor: {
1701 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
1702 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
1703 AD->getDestructorDecl(AC.getASTContext()));
1704 if (!DD->hasAttrs())
1705 break;
1706
1707 // Create a dummy expression,
1708 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001709 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00001710 AD->getTriggerStmt()->getLocEnd());
1711 LocksetBuilder.handleCall(&DRE, DD);
1712 break;
1713 }
1714 default:
1715 break;
1716 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001717 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001718 CurrBlockInfo->ExitSet = LocksetBuilder.LSet;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001719
1720 // For every back edge from CurrBlock (the end of the loop) to another block
1721 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
1722 // the one held at the beginning of FirstLoopBlock. We can look up the
1723 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
1724 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1725 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1726
1727 // if CurrBlock -> *SI is *not* a back edge
1728 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1729 continue;
1730
1731 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001732 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
1733 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
1734 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
1735 PreLoop->EntryLoc,
Richard Smith2e515622012-02-03 04:45:26 +00001736 LEK_LockedSomeLoopIterations);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001737 }
1738 }
1739
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001740 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
1741 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00001742
1743 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001744 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
1745 Final->ExitLoc,
Richard Smith2e515622012-02-03 04:45:26 +00001746 LEK_LockedAtEndOfFunction);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001747}
1748
1749} // end anonymous namespace
1750
1751
1752namespace clang {
1753namespace thread_safety {
1754
1755/// \brief Check a function's CFG for thread-safety violations.
1756///
1757/// We traverse the blocks in the CFG, compute the set of mutexes that are held
1758/// at the end of each block, and issue warnings for thread safety violations.
1759/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00001760void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001761 ThreadSafetyHandler &Handler) {
1762 ThreadSafetyAnalyzer Analyzer(Handler);
1763 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001764}
1765
1766/// \brief Helper function that returns a LockKind required for the given level
1767/// of access.
1768LockKind getLockKindFromAccessKind(AccessKind AK) {
1769 switch (AK) {
1770 case AK_Read :
1771 return LK_Shared;
1772 case AK_Written :
1773 return LK_Exclusive;
1774 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00001775 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001776}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001777
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001778}} // end namespace clang::thread_safety