blob: a986c587f869b25564894699218b8afdb0b03da5 [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"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
Aaron Ballman7c192b42014-05-09 18:26:23 +000026#include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000027#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
DeLesley Hutchins7e615c22014-04-09 22:39:43 +000028#include "clang/Analysis/Analyses/ThreadSafetyTraverse.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 Hutchinsea1f8332014-07-28 15:57:27 +000043#include <ostream>
44#include <sstream>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000045#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000046#include <vector>
47
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000048
49namespace clang {
50namespace threadSafety {
Caitlin Sadowski33208342011-09-09 16:11:56 +000051
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000052// Key method definition
53ThreadSafetyHandler::~ThreadSafetyHandler() {}
54
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000055class TILPrinter :
56 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000057
58
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000059/// Issue a warning about an invalid lock expression
60static void warnInvalidLock(ThreadSafetyHandler &Handler,
61 const Expr *MutexExp, const NamedDecl *D,
62 const Expr *DeclExp, StringRef Kind) {
63 SourceLocation Loc;
64 if (DeclExp)
65 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000066
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000067 // FIXME: add a note about the attribute location in MutexExp or D
68 if (Loc.isValid())
69 Handler.handleInvalidLockExp(Kind, Loc);
70}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000071
Caitlin Sadowski33208342011-09-09 16:11:56 +000072
DeLesley Hutchins42665222014-08-04 16:10:59 +000073/// \brief A set of CapabilityInfo objects, which are compiled from the
74/// requires attributes on a function.
75class CapExprSet : public SmallVector<CapabilityExpr, 4> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000076public:
Aaron Ballmancea26092014-03-06 19:10:16 +000077 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins42665222014-08-04 16:10:59 +000078 void push_back_nodup(const CapabilityExpr &CapE) {
79 iterator It = std::find_if(begin(), end(),
80 [=](const CapabilityExpr &CapE2) {
81 return CapE.equals(CapE2);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000082 });
83 if (It == end())
DeLesley Hutchins42665222014-08-04 16:10:59 +000084 push_back(CapE);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000085 }
86};
87
Ed Schoutenca988742014-09-03 06:00:11 +000088class FactManager;
89class FactSet;
DeLesley Hutchins42665222014-08-04 16:10:59 +000090
91/// \brief This is a helper class that stores a fact that is known at a
92/// particular point in program execution. Currently, a fact is a capability,
93/// along with additional information, such as where it was acquired, whether
94/// it is exclusive or shared, etc.
Caitlin Sadowski33208342011-09-09 16:11:56 +000095///
DeLesley Hutchins42665222014-08-04 16:10:59 +000096/// FIXME: this analysis does not currently support either re-entrant
97/// locking or lock "upgrading" and "downgrading" between exclusive and
98/// shared.
99class FactEntry : public CapabilityExpr {
100private:
NAKAMURA Takumie9882cf2014-08-04 22:48:36 +0000101 LockKind LKind; ///< exclusive or shared
102 SourceLocation AcquireLoc; ///< where it was acquired.
NAKAMURA Takumie9882cf2014-08-04 22:48:36 +0000103 bool Asserted; ///< true if the lock was asserted
Caitlin Sadowski33208342011-09-09 16:11:56 +0000104
DeLesley Hutchins42665222014-08-04 16:10:59 +0000105public:
106 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
Ed Schoutenca988742014-09-03 06:00:11 +0000107 bool Asrt)
108 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt) {}
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000109
Ed Schoutenca988742014-09-03 06:00:11 +0000110 virtual ~FactEntry() {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000111
DeLesley Hutchins42665222014-08-04 16:10:59 +0000112 LockKind kind() const { return LKind; }
113 SourceLocation loc() const { return AcquireLoc; }
114 bool asserted() const { return Asserted; }
Ed Schoutenca988742014-09-03 06:00:11 +0000115
116 virtual void
117 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
118 SourceLocation JoinLoc, LockErrorKind LEK,
119 ThreadSafetyHandler &Handler) const = 0;
120 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
121 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
122 bool FullyRemove, ThreadSafetyHandler &Handler,
123 StringRef DiagKind) const = 0;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000124
DeLesley Hutchins42665222014-08-04 16:10:59 +0000125 // Return true if LKind >= LK, where exclusive > shared
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000126 bool isAtLeast(LockKind LK) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000127 return (LKind == LK_Exclusive) || (LK == LK_Shared);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000128 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000129};
130
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000131
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000132typedef unsigned short FactID;
133
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000134/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000135/// the analysis of a single routine.
136class FactManager {
137private:
Ed Schoutenca988742014-09-03 06:00:11 +0000138 std::vector<std::unique_ptr<FactEntry>> Facts;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000139
140public:
Ed Schoutenca988742014-09-03 06:00:11 +0000141 FactID newFact(std::unique_ptr<FactEntry> Entry) {
142 Facts.push_back(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000143 return static_cast<unsigned short>(Facts.size() - 1);
144 }
145
Ed Schoutenca988742014-09-03 06:00:11 +0000146 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
147 FactEntry &operator[](FactID F) { return *Facts[F]; }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000148};
149
150
151/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000152/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000153/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000154/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000155/// locks, so we can get away with doing a linear search for lookup. Note
156/// that a hashtable or map is inappropriate in this case, because lookups
157/// may involve partial pattern matches, rather than exact matches.
158class FactSet {
159private:
160 typedef SmallVector<FactID, 4> FactVec;
161
162 FactVec FactIDs;
163
164public:
165 typedef FactVec::iterator iterator;
166 typedef FactVec::const_iterator const_iterator;
167
168 iterator begin() { return FactIDs.begin(); }
169 const_iterator begin() const { return FactIDs.begin(); }
170
171 iterator end() { return FactIDs.end(); }
172 const_iterator end() const { return FactIDs.end(); }
173
174 bool isEmpty() const { return FactIDs.size() == 0; }
175
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000176 // Return true if the set contains only negative facts
177 bool isEmpty(FactManager &FactMan) const {
178 for (FactID FID : *this) {
179 if (!FactMan[FID].negative())
180 return false;
181 }
182 return true;
183 }
184
185 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
186
Ed Schoutenca988742014-09-03 06:00:11 +0000187 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
188 FactID F = FM.newFact(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000189 FactIDs.push_back(F);
190 return F;
191 }
192
DeLesley Hutchins42665222014-08-04 16:10:59 +0000193 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000194 unsigned n = FactIDs.size();
195 if (n == 0)
196 return false;
197
198 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000199 if (FM[FactIDs[i]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000200 FactIDs[i] = FactIDs[n-1];
201 FactIDs.pop_back();
202 return true;
203 }
204 }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000205 if (FM[FactIDs[n-1]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000206 FactIDs.pop_back();
207 return true;
208 }
209 return false;
210 }
211
DeLesley Hutchins42665222014-08-04 16:10:59 +0000212 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000213 return std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000214 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000215 });
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000216 }
217
DeLesley Hutchins42665222014-08-04 16:10:59 +0000218 FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000219 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000220 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000221 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000222 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000223 }
224
DeLesley Hutchins42665222014-08-04 16:10:59 +0000225 FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000226 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000227 return FM[ID].matchesUniv(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000228 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000229 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000230 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000231
DeLesley Hutchins42665222014-08-04 16:10:59 +0000232 FactEntry *findPartialMatch(FactManager &FM,
233 const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000234 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000235 return FM[ID].partiallyMatches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000236 });
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000237 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000238 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000239};
240
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000241
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000242typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000243class LocalVariableMap;
244
Richard Smith92286672012-02-03 04:45:26 +0000245/// A side (entry or exit) of a CFG node.
246enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000247
248/// CFGBlockInfo is a struct which contains all the information that is
249/// maintained for each block in the CFG. See LocalVariableMap for more
250/// information about the contexts.
251struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000252 FactSet EntrySet; // Lockset held at entry to block
253 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000254 LocalVarContext EntryContext; // Context held at entry to block
255 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000256 SourceLocation EntryLoc; // Location of first statement in block
257 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000258 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000259 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000260
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000261 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000262 return Side == CBS_Entry ? EntrySet : ExitSet;
263 }
264 SourceLocation getLocation(CFGBlockSide Side) const {
265 return Side == CBS_Entry ? EntryLoc : ExitLoc;
266 }
267
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000268private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000269 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000270 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000271 { }
272
273public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000274 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000275};
276
277
278
279// A LocalVariableMap maintains a map from local variables to their currently
280// valid definitions. It provides SSA-like functionality when traversing the
281// CFG. Like SSA, each definition or assignment to a variable is assigned a
282// unique name (an integer), which acts as the SSA name for that definition.
283// The total set of names is shared among all CFG basic blocks.
284// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
285// with their SSA-names. Instead, we compute a Context for each point in the
286// code, which maps local variables to the appropriate SSA-name. This map
287// changes with each assignment.
288//
289// The map is computed in a single pass over the CFG. Subsequent analyses can
290// then query the map to find the appropriate Context for a statement, and use
291// that Context to look up the definitions of variables.
292class LocalVariableMap {
293public:
294 typedef LocalVarContext Context;
295
296 /// A VarDefinition consists of an expression, representing the value of the
297 /// variable, along with the context in which that expression should be
298 /// interpreted. A reference VarDefinition does not itself contain this
299 /// information, but instead contains a pointer to a previous VarDefinition.
300 struct VarDefinition {
301 public:
302 friend class LocalVariableMap;
303
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000304 const NamedDecl *Dec; // The original declaration for this variable.
305 const Expr *Exp; // The expression for this variable, OR
306 unsigned Ref; // Reference to another VarDefinition
307 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000308
309 bool isReference() { return !Exp; }
310
311 private:
312 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000313 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000314 : Dec(D), Exp(E), Ref(0), Ctx(C)
315 { }
316
317 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000318 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Craig Topper25542942014-05-20 04:30:07 +0000319 : Dec(D), Exp(nullptr), Ref(R), Ctx(C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000320 { }
321 };
322
323private:
324 Context::Factory ContextFactory;
325 std::vector<VarDefinition> VarDefinitions;
326 std::vector<unsigned> CtxIndices;
327 std::vector<std::pair<Stmt*, Context> > SavedContexts;
328
329public:
330 LocalVariableMap() {
331 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000332 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000333 }
334
335 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000336 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000337 const unsigned *i = Ctx.lookup(D);
338 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000339 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000340 assert(*i < VarDefinitions.size());
341 return &VarDefinitions[*i];
342 }
343
344 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000345 /// NULL if the expression is not statically known. If successful, also
346 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000347 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000348 const unsigned *P = Ctx.lookup(D);
349 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000350 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000351
352 unsigned i = *P;
353 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000354 if (VarDefinitions[i].Exp) {
355 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000356 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000357 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000358 i = VarDefinitions[i].Ref;
359 }
Craig Topper25542942014-05-20 04:30:07 +0000360 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000361 }
362
363 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
364
365 /// Return the next context after processing S. This function is used by
366 /// clients of the class to get the appropriate context when traversing the
367 /// CFG. It must be called for every assignment or DeclStmt.
368 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
369 if (SavedContexts[CtxIndex+1].first == S) {
370 CtxIndex++;
371 Context Result = SavedContexts[CtxIndex].second;
372 return Result;
373 }
374 return C;
375 }
376
377 void dumpVarDefinitionName(unsigned i) {
378 if (i == 0) {
379 llvm::errs() << "Undefined";
380 return;
381 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000382 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000383 if (!Dec) {
384 llvm::errs() << "<<NULL>>";
385 return;
386 }
387 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000388 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000389 }
390
391 /// Dumps an ASCII representation of the variable map to llvm::errs()
392 void dump() {
393 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000394 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000395 unsigned Ref = VarDefinitions[i].Ref;
396
397 dumpVarDefinitionName(i);
398 llvm::errs() << " = ";
399 if (Exp) Exp->dump();
400 else {
401 dumpVarDefinitionName(Ref);
402 llvm::errs() << "\n";
403 }
404 }
405 }
406
407 /// Dumps an ASCII representation of a Context to llvm::errs()
408 void dumpContext(Context C) {
409 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000410 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000411 D->printName(llvm::errs());
412 const unsigned *i = C.lookup(D);
413 llvm::errs() << " -> ";
414 dumpVarDefinitionName(*i);
415 llvm::errs() << "\n";
416 }
417 }
418
419 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000420 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
421 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000422
423protected:
424 // Get the current context index
425 unsigned getContextIndex() { return SavedContexts.size()-1; }
426
427 // Save the current context for later replay
428 void saveContext(Stmt *S, Context C) {
429 SavedContexts.push_back(std::make_pair(S,C));
430 }
431
432 // Adds a new definition to the given context, and returns a new context.
433 // This method should be called when declaring a new variable.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000434 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000435 assert(!Ctx.contains(D));
436 unsigned newID = VarDefinitions.size();
437 Context NewCtx = ContextFactory.add(Ctx, D, newID);
438 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
439 return NewCtx;
440 }
441
442 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000443 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000444 unsigned newID = VarDefinitions.size();
445 Context NewCtx = ContextFactory.add(Ctx, D, newID);
446 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
447 return NewCtx;
448 }
449
450 // Updates a definition only if that definition is already in the map.
451 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000452 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000453 if (Ctx.contains(D)) {
454 unsigned newID = VarDefinitions.size();
455 Context NewCtx = ContextFactory.remove(Ctx, D);
456 NewCtx = ContextFactory.add(NewCtx, D, newID);
457 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
458 return NewCtx;
459 }
460 return Ctx;
461 }
462
463 // Removes a definition from the context, but keeps the variable name
464 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000465 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000466 Context NewCtx = Ctx;
467 if (NewCtx.contains(D)) {
468 NewCtx = ContextFactory.remove(NewCtx, D);
469 NewCtx = ContextFactory.add(NewCtx, D, 0);
470 }
471 return NewCtx;
472 }
473
474 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000475 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000476 Context NewCtx = Ctx;
477 if (NewCtx.contains(D)) {
478 NewCtx = ContextFactory.remove(NewCtx, D);
479 }
480 return NewCtx;
481 }
482
483 Context intersectContexts(Context C1, Context C2);
484 Context createReferenceContext(Context C);
485 void intersectBackEdge(Context C1, Context C2);
486
487 friend class VarMapBuilder;
488};
489
490
491// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000492CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
493 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000494}
495
496
497/// Visitor which builds a LocalVariableMap
498class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
499public:
500 LocalVariableMap* VMap;
501 LocalVariableMap::Context Ctx;
502
503 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
504 : VMap(VM), Ctx(C) {}
505
506 void VisitDeclStmt(DeclStmt *S);
507 void VisitBinaryOperator(BinaryOperator *BO);
508};
509
510
511// Add new local variables to the variable map
512void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
513 bool modifiedCtx = false;
514 DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000515 for (const auto *D : DGrp) {
516 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
517 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000518
519 // Add local variables with trivial type to the variable map
520 QualType T = VD->getType();
521 if (T.isTrivialType(VD->getASTContext())) {
522 Ctx = VMap->addDefinition(VD, E, Ctx);
523 modifiedCtx = true;
524 }
525 }
526 }
527 if (modifiedCtx)
528 VMap->saveContext(S, Ctx);
529}
530
531// Update local variable definitions in variable map
532void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
533 if (!BO->isAssignmentOp())
534 return;
535
536 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
537
538 // Update the variable map and current context.
539 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
540 ValueDecl *VDec = DRE->getDecl();
541 if (Ctx.lookup(VDec)) {
542 if (BO->getOpcode() == BO_Assign)
543 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
544 else
545 // FIXME -- handle compound assignment operators
546 Ctx = VMap->clearDefinition(VDec, Ctx);
547 VMap->saveContext(BO, Ctx);
548 }
549 }
550}
551
552
553// Computes the intersection of two contexts. The intersection is the
554// set of variables which have the same definition in both contexts;
555// variables with different definitions are discarded.
556LocalVariableMap::Context
557LocalVariableMap::intersectContexts(Context C1, Context C2) {
558 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000559 for (const auto &P : C1) {
560 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000561 const unsigned *i2 = C2.lookup(Dec);
562 if (!i2) // variable doesn't exist on second path
563 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000564 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000565 Result = clearDefinition(Dec, Result);
566 }
567 return Result;
568}
569
570// For every variable in C, create a new variable that refers to the
571// definition in C. Return a new context that contains these new variables.
572// (We use this for a naive implementation of SSA on loop back-edges.)
573LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
574 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000575 for (const auto &P : C)
576 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000577 return Result;
578}
579
580// This routine also takes the intersection of C1 and C2, but it does so by
581// altering the VarDefinitions. C1 must be the result of an earlier call to
582// createReferenceContext.
583void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000584 for (const auto &P : C1) {
585 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000586 VarDefinition *VDef = &VarDefinitions[i1];
587 assert(VDef->isReference());
588
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000589 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000590 if (!i2 || (*i2 != i1))
591 VDef->Ref = 0; // Mark this variable as undefined
592 }
593}
594
595
596// Traverse the CFG in topological order, so all predecessors of a block
597// (excluding back-edges) are visited before the block itself. At
598// each point in the code, we calculate a Context, which holds the set of
599// variable definitions which are visible at that point in execution.
600// Visible variables are mapped to their definitions using an array that
601// contains all definitions.
602//
603// At join points in the CFG, the set is computed as the intersection of
604// the incoming sets along each edge, E.g.
605//
606// { Context | VarDefinitions }
607// int x = 0; { x -> x1 | x1 = 0 }
608// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
609// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
610// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
611// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
612//
613// This is essentially a simpler and more naive version of the standard SSA
614// algorithm. Those definitions that remain in the intersection are from blocks
615// that strictly dominate the current block. We do not bother to insert proper
616// phi nodes, because they are not used in our analysis; instead, wherever
617// a phi node would be required, we simply remove that definition from the
618// context (E.g. x above).
619//
620// The initial traversal does not capture back-edges, so those need to be
621// handled on a separate pass. Whenever the first pass encounters an
622// incoming back edge, it duplicates the context, creating new definitions
623// that refer back to the originals. (These correspond to places where SSA
624// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000625// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000626// node was actually required.) E.g.
627//
628// { Context | VarDefinitions }
629// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
630// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
631// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
632// ... { y -> y1 | x3 = 2, x2 = 1, ... }
633//
634void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000635 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000636 std::vector<CFGBlockInfo> &BlockInfo) {
637 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
638
639 CtxIndices.resize(CFGraph->getNumBlockIDs());
640
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000641 for (const auto *CurrBlock : *SortedGraph) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000642 int CurrBlockID = CurrBlock->getBlockID();
643 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
644
645 VisitedBlocks.insert(CurrBlock);
646
647 // Calculate the entry context for the current block
648 bool HasBackEdges = false;
649 bool CtxInit = true;
650 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
651 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
652 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000653 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000654 HasBackEdges = true;
655 continue;
656 }
657
658 int PrevBlockID = (*PI)->getBlockID();
659 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
660
661 if (CtxInit) {
662 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
663 CtxInit = false;
664 }
665 else {
666 CurrBlockInfo->EntryContext =
667 intersectContexts(CurrBlockInfo->EntryContext,
668 PrevBlockInfo->ExitContext);
669 }
670 }
671
672 // Duplicate the context if we have back-edges, so we can call
673 // intersectBackEdges later.
674 if (HasBackEdges)
675 CurrBlockInfo->EntryContext =
676 createReferenceContext(CurrBlockInfo->EntryContext);
677
678 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000679 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000680 CurrBlockInfo->EntryIndex = getContextIndex();
681
682 // Visit all the statements in the basic block.
683 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
684 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
685 BE = CurrBlock->end(); BI != BE; ++BI) {
686 switch (BI->getKind()) {
687 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +0000688 CFGStmt CS = BI->castAs<CFGStmt>();
689 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000690 break;
691 }
692 default:
693 break;
694 }
695 }
696 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
697
698 // Mark variables on back edges as "unknown" if they've been changed.
699 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
700 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
701 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000702 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000703 continue;
704
705 CFGBlock *FirstLoopBlock = *SI;
706 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
707 Context LoopEnd = CurrBlockInfo->ExitContext;
708 intersectBackEdge(LoopBegin, LoopEnd);
709 }
710 }
711
712 // Put an extra entry at the end of the indexed context array
713 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000714 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000715}
716
Richard Smith92286672012-02-03 04:45:26 +0000717/// Find the appropriate source locations to use when producing diagnostics for
718/// each block in the CFG.
719static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000720 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000721 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000722 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000723 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
724
725 // Find the source location of the last statement in the block, if the
726 // block is not empty.
727 if (const Stmt *S = CurrBlock->getTerminator()) {
728 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
729 } else {
730 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
731 BE = CurrBlock->rend(); BI != BE; ++BI) {
732 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000733 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
734 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000735 break;
736 }
737 }
738 }
739
740 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
741 // This block contains at least one statement. Find the source location
742 // of the first statement in the block.
743 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
744 BE = CurrBlock->end(); BI != BE; ++BI) {
745 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000746 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
747 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000748 break;
749 }
750 }
751 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
752 CurrBlock != &CFGraph->getExit()) {
753 // The block is empty, and has a single predecessor. Use its exit
754 // location.
755 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
756 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
757 }
758 }
759}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000760
Ed Schoutenca988742014-09-03 06:00:11 +0000761class LockableFactEntry : public FactEntry {
762private:
763 bool Managed; ///< managed by ScopedLockable object
764
765public:
766 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
767 bool Mng = false, bool Asrt = false)
768 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
769
770 void
771 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
772 SourceLocation JoinLoc, LockErrorKind LEK,
773 ThreadSafetyHandler &Handler) const override {
774 if (!Managed && !asserted() && !negative() && !isUniversal()) {
775 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
776 LEK);
777 }
778 }
779
780 void handleUnlock(FactSet &FSet, FactManager &FactMan,
781 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
782 bool FullyRemove, ThreadSafetyHandler &Handler,
783 StringRef DiagKind) const override {
784 FSet.removeLock(FactMan, Cp);
785 if (!Cp.negative()) {
786 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
787 !Cp, LK_Exclusive, UnlockLoc));
788 }
789 }
790};
791
792class ScopedLockableFactEntry : public FactEntry {
793private:
794 SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
795
796public:
797 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
798 const CapExprSet &Excl, const CapExprSet &Shrd)
799 : FactEntry(CE, LK_Exclusive, Loc, false) {
800 for (const auto &M : Excl)
801 UnderlyingMutexes.push_back(M.sexpr());
802 for (const auto &M : Shrd)
803 UnderlyingMutexes.push_back(M.sexpr());
804 }
805
806 void
807 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
808 SourceLocation JoinLoc, LockErrorKind LEK,
809 ThreadSafetyHandler &Handler) const override {
810 for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
811 if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
812 // If this scoped lock manages another mutex, and if the underlying
813 // mutex is still held, then warn about the underlying mutex.
814 Handler.handleMutexHeldEndOfScope(
815 "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
816 }
817 }
818 }
819
820 void handleUnlock(FactSet &FSet, FactManager &FactMan,
821 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
822 bool FullyRemove, ThreadSafetyHandler &Handler,
823 StringRef DiagKind) const override {
824 assert(!Cp.negative() && "Managing object cannot be negative.");
825 for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
826 CapabilityExpr UnderCp(UnderlyingMutex, false);
827 auto UnderEntry = llvm::make_unique<LockableFactEntry>(
828 !UnderCp, LK_Exclusive, UnlockLoc);
829
830 if (FullyRemove) {
831 // We're destroying the managing object.
832 // Remove the underlying mutex if it exists; but don't warn.
833 if (FSet.findLock(FactMan, UnderCp)) {
834 FSet.removeLock(FactMan, UnderCp);
835 FSet.addLock(FactMan, std::move(UnderEntry));
836 }
837 } else {
838 // We're releasing the underlying mutex, but not destroying the
839 // managing object. Warn on dual release.
840 if (!FSet.findLock(FactMan, UnderCp)) {
841 Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
842 UnlockLoc);
843 }
844 FSet.removeLock(FactMan, UnderCp);
845 FSet.addLock(FactMan, std::move(UnderEntry));
846 }
847 }
848 if (FullyRemove)
849 FSet.removeLock(FactMan, Cp);
850 }
851};
852
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000853/// \brief Class which implements the core thread safety analysis routines.
854class ThreadSafetyAnalyzer {
855 friend class BuildLockset;
856
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000857 llvm::BumpPtrAllocator Bpa;
858 threadSafety::til::MemRegionRef Arena;
859 threadSafety::SExprBuilder SxBuilder;
860
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000861 ThreadSafetyHandler &Handler;
DeLesley Hutchins42665222014-08-04 16:10:59 +0000862 const CXXMethodDecl *CurrentMethod;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000863 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000864 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000865 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000866
867public:
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000868 ThreadSafetyAnalyzer(ThreadSafetyHandler &H)
869 : Arena(&Bpa), SxBuilder(Arena), Handler(H) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000870
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000871 bool inCurrentScope(const CapabilityExpr &CapE);
872
Ed Schoutenca988742014-09-03 06:00:11 +0000873 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
874 StringRef DiagKind, bool ReqAttr = false);
DeLesley Hutchins42665222014-08-04 16:10:59 +0000875 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000876 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
877 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000878
879 template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000880 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +0000881 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000882
883 template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000884 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000885 const NamedDecl *D,
886 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
887 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000888
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000889 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
890 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000891
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000892 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
893 const CFGBlock* PredBlock,
894 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +0000895
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000896 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
897 SourceLocation JoinLoc,
898 LockErrorKind LEK1, LockErrorKind LEK2,
899 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000900
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000901 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
902 SourceLocation JoinLoc, LockErrorKind LEK1,
903 bool Modify=true) {
904 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000905 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000906
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000907 void runAnalysis(AnalysisDeclContext &AC);
908};
909
Aaron Ballmane0449042014-04-01 21:43:23 +0000910/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
911static const ValueDecl *getValueDecl(const Expr *Exp) {
912 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
913 return getValueDecl(CE->getSubExpr());
914
915 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
916 return DR->getDecl();
917
918 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
919 return ME->getMemberDecl();
920
921 return nullptr;
922}
923
924template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000925class has_arg_iterator_range {
Aaron Ballmane0449042014-04-01 21:43:23 +0000926 typedef char yes[1];
927 typedef char no[2];
928
929 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000930 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +0000931
932 template <typename>
933 static no& test(...);
934
935public:
936 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
937};
938
939static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
940 return A->getName();
941}
942
943static StringRef ClassifyDiagnostic(QualType VDT) {
944 // We need to look at the declaration of the type of the value to determine
945 // which it is. The type should either be a record or a typedef, or a pointer
946 // or reference thereof.
947 if (const auto *RT = VDT->getAs<RecordType>()) {
948 if (const auto *RD = RT->getDecl())
949 if (const auto *CA = RD->getAttr<CapabilityAttr>())
950 return ClassifyDiagnostic(CA);
951 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
952 if (const auto *TD = TT->getDecl())
953 if (const auto *CA = TD->getAttr<CapabilityAttr>())
954 return ClassifyDiagnostic(CA);
955 } else if (VDT->isPointerType() || VDT->isReferenceType())
956 return ClassifyDiagnostic(VDT->getPointeeType());
957
958 return "mutex";
959}
960
961static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
962 assert(VD && "No ValueDecl passed");
963
964 // The ValueDecl is the declaration of a mutex or role (hopefully).
965 return ClassifyDiagnostic(VD->getType());
966}
967
968template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000969static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +0000970 StringRef>::type
971ClassifyDiagnostic(const AttrTy *A) {
972 if (const ValueDecl *VD = getValueDecl(A->getArg()))
973 return ClassifyDiagnostic(VD);
974 return "mutex";
975}
976
977template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000978static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +0000979 StringRef>::type
980ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000981 for (const auto *Arg : A->args()) {
982 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +0000983 return ClassifyDiagnostic(VD);
984 }
985 return "mutex";
986}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000987
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000988
989inline bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
990 if (!CurrentMethod)
991 return false;
992 if (auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
993 auto *VD = P->clangDecl();
994 if (VD)
995 return VD->getDeclContext() == CurrentMethod->getDeclContext();
996 }
997 return false;
998}
999
1000
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001001/// \brief Add a new lock to the lockset, warning if the lock is already there.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001002/// \param ReqAttr -- true if this is part of an initial Requires attribute.
Ed Schoutenca988742014-09-03 06:00:11 +00001003void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1004 std::unique_ptr<FactEntry> Entry,
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001005 StringRef DiagKind, bool ReqAttr) {
Ed Schoutenca988742014-09-03 06:00:11 +00001006 if (Entry->shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001007 return;
1008
Ed Schoutenca988742014-09-03 06:00:11 +00001009 if (!ReqAttr && !Entry->negative()) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001010 // look for the negative capability, and remove it from the fact set.
Ed Schoutenca988742014-09-03 06:00:11 +00001011 CapabilityExpr NegC = !*Entry;
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001012 FactEntry *Nen = FSet.findLock(FactMan, NegC);
1013 if (Nen) {
1014 FSet.removeLock(FactMan, NegC);
1015 }
1016 else {
Ed Schoutenca988742014-09-03 06:00:11 +00001017 if (inCurrentScope(*Entry) && !Entry->asserted())
1018 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1019 NegC.toString(), Entry->loc());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001020 }
1021 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001022
1023 // FIXME: deal with acquired before/after annotations.
1024 // FIXME: Don't always warn when we have support for reentrant locks.
Ed Schoutenca988742014-09-03 06:00:11 +00001025 if (FSet.findLock(FactMan, *Entry)) {
1026 if (!Entry->asserted())
1027 Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001028 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001029 FSet.addLock(FactMan, std::move(Entry));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001030 }
1031}
1032
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001033
1034/// \brief Remove a lock from the lockset, warning if the lock is not there.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001035/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001036void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001037 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001038 bool FullyRemove, LockKind ReceivedKind,
1039 StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001040 if (Cp.shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001041 return;
1042
DeLesley Hutchins42665222014-08-04 16:10:59 +00001043 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001044 if (!LDat) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001045 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001046 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001047 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001048
Aaron Ballmandf115d92014-03-21 14:48:48 +00001049 // Generic lock removal doesn't care about lock kind mismatches, but
1050 // otherwise diagnose when the lock kinds are mismatched.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001051 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1052 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1053 LDat->kind(), ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001054 }
1055
Ed Schoutenca988742014-09-03 06:00:11 +00001056 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1057 DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001058}
1059
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001060
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001061/// \brief Extract the list of mutexIDs from the attribute on an expression,
1062/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001063template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001064void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001065 Expr *Exp, const NamedDecl *D,
1066 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001067 if (Attr->args_size() == 0) {
1068 // The mutex held is the "this" object.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001069 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1070 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001071 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1072 return;
1073 }
1074 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001075 if (!Cp.shouldIgnore())
1076 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001077 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001078 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001079
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001080 for (const auto *Arg : Attr->args()) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001081 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1082 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001083 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
DeLesley Hutchins42665222014-08-04 16:10:59 +00001084 continue;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001085 }
1086 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001087 if (!Cp.shouldIgnore())
1088 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001089 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001090}
1091
1092
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001093/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1094/// trylock applies to the given edge, then push them onto Mtxs, discarding
1095/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001096template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001097void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001098 Expr *Exp, const NamedDecl *D,
1099 const CFGBlock *PredBlock,
1100 const CFGBlock *CurrBlock,
1101 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001102 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001103 bool branch = false;
1104 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001105 branch = BLE->getValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001106 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001107 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001108
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001109 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001110 if (Neg)
1111 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001112
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001113 // If we've taken the trylock branch, then add the lock
1114 int i = 0;
1115 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1116 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001117 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001118 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001119 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001120}
1121
1122
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001123bool getStaticBooleanValue(Expr* E, bool& TCond) {
1124 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1125 TCond = false;
1126 return true;
1127 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1128 TCond = BLE->getValue();
1129 return true;
1130 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1131 TCond = ILE->getValue().getBoolValue();
1132 return true;
1133 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1134 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1135 }
1136 return false;
1137}
1138
1139
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001140// If Cond can be traced back to a function call, return the call expression.
1141// The negate variable should be called with false, and will be set to true
1142// if the function call is negated, e.g. if (!mu.tryLock(...))
1143const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1144 LocalVarContext C,
1145 bool &Negate) {
1146 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001147 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001148
1149 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1150 return CallExp;
1151 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001152 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1153 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1154 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001155 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1156 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1157 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001158 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1159 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1160 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001161 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1162 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1163 return getTrylockCallExpr(E, C, Negate);
1164 }
1165 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1166 if (UOP->getOpcode() == UO_LNot) {
1167 Negate = !Negate;
1168 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1169 }
Craig Topper25542942014-05-20 04:30:07 +00001170 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001171 }
1172 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1173 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1174 if (BOP->getOpcode() == BO_NE)
1175 Negate = !Negate;
1176
1177 bool TCond = false;
1178 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1179 if (!TCond) Negate = !Negate;
1180 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1181 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001182 TCond = false;
1183 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001184 if (!TCond) Negate = !Negate;
1185 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1186 }
Craig Topper25542942014-05-20 04:30:07 +00001187 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001188 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001189 if (BOP->getOpcode() == BO_LAnd) {
1190 // LHS must have been evaluated in a different block.
1191 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1192 }
1193 if (BOP->getOpcode() == BO_LOr) {
1194 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1195 }
Craig Topper25542942014-05-20 04:30:07 +00001196 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001197 }
Craig Topper25542942014-05-20 04:30:07 +00001198 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001199}
1200
1201
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001202/// \brief Find the lockset that holds on the edge between PredBlock
1203/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1204/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001205void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1206 const FactSet &ExitSet,
1207 const CFGBlock *PredBlock,
1208 const CFGBlock *CurrBlock) {
1209 Result = ExitSet;
1210
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001211 const Stmt *Cond = PredBlock->getTerminatorCondition();
1212 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001213 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001214
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001215 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001216 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1217 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001218 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001219
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001220 CallExpr *Exp =
1221 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001222 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001223 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001224
1225 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1226 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001227 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001228
DeLesley Hutchins42665222014-08-04 16:10:59 +00001229 CapExprSet ExclusiveLocksToAdd;
1230 CapExprSet SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001231
1232 // If the condition is a call to a Trylock function, then grab the attributes
Aaron Ballman9ee54d12014-05-14 20:42:13 +00001233 for (auto *Attr : FunDecl->getAttrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001234 switch (Attr->getKind()) {
1235 case attr::ExclusiveTrylockFunction: {
1236 ExclusiveTrylockFunctionAttr *A =
1237 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001238 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1239 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001240 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001241 break;
1242 }
1243 case attr::SharedTrylockFunction: {
1244 SharedTrylockFunctionAttr *A =
1245 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001246 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001247 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001248 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001249 break;
1250 }
1251 default:
1252 break;
1253 }
1254 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001255
1256 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001257 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001258 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001259 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1260 LK_Exclusive, Loc),
Aaron Ballmane0449042014-04-01 21:43:23 +00001261 CapDiagKind);
1262 for (const auto &SharedLockToAdd : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001263 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1264 LK_Shared, Loc),
DeLesley Hutchins42665222014-08-04 16:10:59 +00001265 CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001266}
1267
Caitlin Sadowski33208342011-09-09 16:11:56 +00001268/// \brief We use this class to visit different types of expressions in
1269/// CFGBlocks, and build up the lockset.
1270/// An expression may cause us to add or remove locks from the lockset, or else
1271/// output error messages related to missing locks.
1272/// FIXME: In future, we may be able to not inherit from a visitor.
1273class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001274 friend class ThreadSafetyAnalyzer;
1275
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001276 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001277 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001278 LocalVariableMap::Context LVarCtx;
1279 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001280
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001281 // helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001282 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001283 Expr *MutexExp, ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001284 StringRef DiagKind, SourceLocation Loc);
Aaron Ballmane0449042014-04-01 21:43:23 +00001285 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1286 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001287
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001288 void checkAccess(const Expr *Exp, AccessKind AK,
1289 ProtectedOperationKind POK = POK_VarAccess);
1290 void checkPtAccess(const Expr *Exp, AccessKind AK,
1291 ProtectedOperationKind POK = POK_VarAccess);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001292
Craig Topper25542942014-05-20 04:30:07 +00001293 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001294
Caitlin Sadowski33208342011-09-09 16:11:56 +00001295public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001296 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001297 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001298 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001299 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001300 LVarCtx(Info.EntryContext),
1301 CtxIndex(Info.EntryIndex)
1302 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001303
1304 void VisitUnaryOperator(UnaryOperator *UO);
1305 void VisitBinaryOperator(BinaryOperator *BO);
1306 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001307 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001308 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001309 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001310};
1311
DeLesley Hutchins42665222014-08-04 16:10:59 +00001312
Caitlin Sadowski33208342011-09-09 16:11:56 +00001313/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001314/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001315void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001316 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001317 ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001318 StringRef DiagKind, SourceLocation Loc) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001319 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001320
DeLesley Hutchins42665222014-08-04 16:10:59 +00001321 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1322 if (Cp.isInvalid()) {
1323 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001324 return;
DeLesley Hutchins42665222014-08-04 16:10:59 +00001325 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001326 return;
1327 }
1328
DeLesley Hutchins42665222014-08-04 16:10:59 +00001329 if (Cp.negative()) {
1330 // Negative capabilities act like locks excluded
1331 FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1332 if (LDat) {
1333 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001334 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001335 return;
1336 }
1337
1338 // If this does not refer to a negative capability in the same class,
1339 // then stop here.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001340 if (!Analyzer->inCurrentScope(Cp))
DeLesley Hutchins42665222014-08-04 16:10:59 +00001341 return;
1342
1343 // Otherwise the negative requirement must be propagated to the caller.
1344 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1345 if (!LDat) {
1346 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001347 LK_Shared, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001348 }
1349 return;
1350 }
1351
1352 FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001353 bool NoError = true;
1354 if (!LDat) {
1355 // No exact match found. Look for a partial match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001356 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1357 if (LDat) {
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001358 // Warn that there's no precise match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001359 std::string PartMatchStr = LDat->toString();
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001360 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001361 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1362 LK, Loc, &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001363 } else {
1364 // Warn that there's no match at all.
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001365 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1366 LK, Loc);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001367 }
1368 NoError = false;
1369 }
1370 // Make sure the mutex we found is the right kind.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001371 if (NoError && LDat && !LDat->isAtLeast(LK)) {
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001372 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1373 LK, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001374 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001375}
1376
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001377/// \brief Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001378void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001379 Expr *MutexExp, StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001380 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1381 if (Cp.isInvalid()) {
1382 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1383 return;
1384 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001385 return;
1386 }
1387
DeLesley Hutchins42665222014-08-04 16:10:59 +00001388 FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
1389 if (LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001390 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins42665222014-08-04 16:10:59 +00001391 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1392 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001393}
1394
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001395/// \brief Checks guarded_by and pt_guarded_by attributes.
1396/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1397/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1398/// Similarly, we check if the access is to an expression that dereferences
1399/// a pointer marked with pt_guarded_by.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001400void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1401 ProtectedOperationKind POK) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001402 Exp = Exp->IgnoreParenCasts();
1403
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001404 SourceLocation Loc = Exp->getExprLoc();
1405
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001406 // Local variables of reference type cannot be re-assigned;
1407 // map them to their initializer.
1408 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1409 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1410 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1411 if (const auto *E = VD->getInit()) {
1412 Exp = E;
1413 continue;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001414 }
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001415 }
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001416 break;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001417 }
1418
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001419 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1420 // For dereferences
1421 if (UO->getOpcode() == clang::UO_Deref)
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001422 checkPtAccess(UO->getSubExpr(), AK, POK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001423 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001424 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001425
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001426 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001427 checkPtAccess(AE->getLHS(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001428 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001429 }
1430
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001431 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1432 if (ME->isArrow())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001433 checkPtAccess(ME->getBase(), AK, POK);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001434 else
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001435 checkAccess(ME->getBase(), AK, POK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001436 }
1437
Caitlin Sadowski33208342011-09-09 16:11:56 +00001438 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001439 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001440 return;
1441
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001442 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001443 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001444 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001445
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001446 for (const auto *I : D->specific_attrs<GuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001447 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001448 ClassifyDiagnostic(I), Loc);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001449}
1450
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001451
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001452/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001453/// POK is the same operationKind that was passed to checkAccess.
1454void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1455 ProtectedOperationKind POK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001456 while (true) {
1457 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1458 Exp = PE->getSubExpr();
1459 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001460 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001461 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1462 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1463 // If it's an actual array, and not a pointer, then it's elements
1464 // are protected by GUARDED_BY, not PT_GUARDED_BY;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001465 checkAccess(CE->getSubExpr(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001466 return;
1467 }
1468 Exp = CE->getSubExpr();
1469 continue;
1470 }
1471 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001472 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001473
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001474 // Pass by reference warnings are under a different flag.
1475 ProtectedOperationKind PtPOK = POK_VarDereference;
1476 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1477
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001478 const ValueDecl *D = getValueDecl(Exp);
1479 if (!D || !D->hasAttrs())
1480 return;
1481
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001482 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001483 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001484 Exp->getExprLoc());
1485
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001486 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001487 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001488 ClassifyDiagnostic(I), Exp->getExprLoc());
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001489}
1490
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001491/// \brief Process a function call, method call, constructor call,
1492/// or destructor call. This involves looking at the attributes on the
1493/// corresponding function/method/constructor/destructor, issuing warnings,
1494/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001495///
1496/// FIXME: For classes annotated with one of the guarded annotations, we need
1497/// to treat const method calls as reads and non-const method calls as writes,
1498/// and check that the appropriate locks are held. Non-const method calls with
1499/// the same signature as const method calls can be also treated as reads.
1500///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001501void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001502 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001503 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins42665222014-08-04 16:10:59 +00001504 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1505 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
Aaron Ballmane0449042014-04-01 21:43:23 +00001506 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001507
Caitlin Sadowski33208342011-09-09 16:11:56 +00001508 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001509 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1510 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001511 // When we encounter a lock function, we need to add the lock to our
1512 // lockset.
1513 case attr::AcquireCapability: {
1514 auto *A = cast<AcquireCapabilityAttr>(At);
1515 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1516 : ExclusiveLocksToAdd,
1517 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001518
1519 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001520 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001521 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001522
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001523 // An assert will add a lock to the lockset, but will not generate
1524 // a warning if it is already there, and will not generate a warning
1525 // if it is not removed.
1526 case attr::AssertExclusiveLock: {
1527 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
1528
DeLesley Hutchins42665222014-08-04 16:10:59 +00001529 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001530 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001531 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001532 Analyzer->addLock(FSet,
1533 llvm::make_unique<LockableFactEntry>(
1534 AssertLock, LK_Exclusive, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001535 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001536 break;
1537 }
1538 case attr::AssertSharedLock: {
1539 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
1540
DeLesley Hutchins42665222014-08-04 16:10:59 +00001541 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001542 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001543 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001544 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1545 AssertLock, LK_Shared, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001546 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001547 break;
1548 }
1549
Caitlin Sadowski33208342011-09-09 16:11:56 +00001550 // When we encounter an unlock function, we need to remove unlocked
1551 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001552 case attr::ReleaseCapability: {
1553 auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001554 if (A->isGeneric())
1555 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1556 else if (A->isShared())
1557 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1558 else
1559 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001560
1561 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001562 break;
1563 }
1564
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001565 case attr::RequiresCapability: {
1566 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001567 for (auto *Arg : A->args())
1568 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001569 POK_FunctionCall, ClassifyDiagnostic(A),
1570 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001571 break;
1572 }
1573
1574 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001575 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001576 for (auto *Arg : A->args())
1577 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001578 break;
1579 }
1580
Alp Tokerd4733632013-12-05 04:47:09 +00001581 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001582 default:
1583 break;
1584 }
1585 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001586
1587 // Figure out if we're calling the constructor of scoped lockable class
1588 bool isScopedVar = false;
1589 if (VD) {
1590 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1591 const CXXRecordDecl* PD = CD->getParent();
Aaron Ballman9ead1242013-12-19 02:39:40 +00001592 if (PD && PD->hasAttr<ScopedLockableAttr>())
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001593 isScopedVar = true;
1594 }
1595 }
1596
1597 // Add locks.
Aaron Ballmandf115d92014-03-21 14:48:48 +00001598 for (const auto &M : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001599 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1600 M, LK_Exclusive, Loc, isScopedVar),
Aaron Ballmane0449042014-04-01 21:43:23 +00001601 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001602 for (const auto &M : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001603 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1604 M, LK_Shared, Loc, isScopedVar),
Aaron Ballmane0449042014-04-01 21:43:23 +00001605 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001606
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001607 if (isScopedVar) {
Ed Schoutenca988742014-09-03 06:00:11 +00001608 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001609 SourceLocation MLoc = VD->getLocation();
1610 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins42665222014-08-04 16:10:59 +00001611 // FIXME: does this store a pointer to DRE?
1612 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001613
Ed Schoutenca988742014-09-03 06:00:11 +00001614 CapExprSet UnderlyingMutexes(ExclusiveLocksToAdd);
1615 std::copy(SharedLocksToAdd.begin(), SharedLocksToAdd.end(),
1616 std::back_inserter(UnderlyingMutexes));
1617 Analyzer->addLock(FSet,
1618 llvm::make_unique<ScopedLockableFactEntry>(
1619 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1620 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001621 }
1622
1623 // Remove locks.
1624 // FIXME -- should only fully remove if the attribute refers to 'this'.
1625 bool Dtor = isa<CXXDestructorDecl>(D);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001626 for (const auto &M : ExclusiveLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001627 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001628 for (const auto &M : SharedLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001629 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001630 for (const auto &M : GenericLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001631 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001632}
1633
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001634
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001635/// \brief For unary operations which read and write a variable, we need to
1636/// check whether we hold any required mutexes. Reads are checked in
1637/// VisitCastExpr.
1638void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1639 switch (UO->getOpcode()) {
1640 case clang::UO_PostDec:
1641 case clang::UO_PostInc:
1642 case clang::UO_PreDec:
1643 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001644 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001645 break;
1646 }
1647 default:
1648 break;
1649 }
1650}
1651
1652/// For binary operations which assign to a variable (writes), we need to check
1653/// whether we hold any required mutexes.
1654/// FIXME: Deal with non-primitive types.
1655void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1656 if (!BO->isAssignmentOp())
1657 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001658
1659 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001660 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001661
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001662 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001663}
1664
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001665
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001666/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1667/// need to ensure we hold any required mutexes.
1668/// FIXME: Deal with non-primitive types.
1669void BuildLockset::VisitCastExpr(CastExpr *CE) {
1670 if (CE->getCastKind() != CK_LValueToRValue)
1671 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001672 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001673}
1674
1675
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001676void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001677 bool ExamineArgs = true;
1678 bool OperatorFun = false;
1679
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001680 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1681 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
1682 // ME can be null when calling a method pointer
1683 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001684
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001685 if (ME && MD) {
1686 if (ME->isArrow()) {
1687 if (MD->isConst()) {
1688 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1689 } else { // FIXME -- should be AK_Written
1690 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001691 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001692 } else {
1693 if (MD->isConst())
1694 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1695 else // FIXME -- should be AK_Written
1696 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001697 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001698 }
1699 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001700 OperatorFun = true;
1701
1702 auto OEop = OE->getOperator();
1703 switch (OEop) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001704 case OO_Equal: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001705 ExamineArgs = false;
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001706 const Expr *Target = OE->getArg(0);
1707 const Expr *Source = OE->getArg(1);
1708 checkAccess(Target, AK_Written);
1709 checkAccess(Source, AK_Read);
1710 break;
1711 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001712 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001713 case OO_Arrow:
1714 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001715 const Expr *Obj = OE->getArg(0);
1716 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001717 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1718 // Grrr. operator* can be multiplication...
1719 checkPtAccess(Obj, AK_Read);
1720 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001721 break;
1722 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001723 default: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001724 // TODO: get rid of this, and rely on pass-by-ref instead.
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00001725 const Expr *Obj = OE->getArg(0);
1726 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001727 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001728 }
1729 }
1730 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001731
1732
1733 if (ExamineArgs) {
1734 if (FunctionDecl *FD = Exp->getDirectCallee()) {
1735 unsigned Fn = FD->getNumParams();
1736 unsigned Cn = Exp->getNumArgs();
1737 unsigned Skip = 0;
1738
1739 unsigned i = 0;
1740 if (OperatorFun) {
1741 if (isa<CXXMethodDecl>(FD)) {
1742 // First arg in operator call is implicit self argument,
1743 // and doesn't appear in the FunctionDecl.
1744 Skip = 1;
1745 Cn--;
1746 } else {
1747 // Ignore the first argument of operators; it's been checked above.
1748 i = 1;
1749 }
1750 }
1751 // Ignore default arguments
1752 unsigned n = (Fn < Cn) ? Fn : Cn;
1753
1754 for (; i < n; ++i) {
1755 ParmVarDecl* Pvd = FD->getParamDecl(i);
1756 Expr* Arg = Exp->getArg(i+Skip);
1757 QualType Qt = Pvd->getType();
1758 if (Qt->isReferenceType())
1759 checkAccess(Arg, AK_Read, POK_PassByRef);
1760 }
1761 }
1762 }
1763
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001764 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1765 if(!D || !D->hasAttrs())
1766 return;
1767 handleCall(Exp, D);
1768}
1769
1770void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001771 const CXXConstructorDecl *D = Exp->getConstructor();
1772 if (D && D->isCopyConstructor()) {
1773 const Expr* Source = Exp->getArg(0);
1774 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001775 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001776 // FIXME -- only handles constructors in DeclStmt below.
1777}
1778
1779void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001780 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001781 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001782
Aaron Ballman9ee54d12014-05-14 20:42:13 +00001783 for (auto *D : S->getDeclGroup()) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001784 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1785 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00001786 // handle constructors that involve temporaries
1787 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1788 E = EWC->getSubExpr();
1789
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001790 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1791 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1792 if (!CtorD || !CtorD->hasAttrs())
1793 return;
1794 handleCall(CE, CtorD, VD);
1795 }
1796 }
1797 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001798}
1799
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00001800
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001801
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001802/// \brief Compute the intersection of two locksets and issue warnings for any
1803/// locks in the symmetric difference.
1804///
1805/// This function is used at a merge point in the CFG when comparing the lockset
1806/// of each branch being merged. For example, given the following sequence:
1807/// A; if () then B; else C; D; we need to check that the lockset after B and C
1808/// are the same. In the event of a difference, we use the intersection of these
1809/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001810///
Ted Kremenek78094ca2012-08-22 23:50:41 +00001811/// \param FSet1 The first lockset.
1812/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001813/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001814/// \param LEK1 The error message to report if a mutex is missing from LSet1
1815/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001816void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
1817 const FactSet &FSet2,
1818 SourceLocation JoinLoc,
1819 LockErrorKind LEK1,
1820 LockErrorKind LEK2,
1821 bool Modify) {
1822 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001823
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001824 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00001825 for (const auto &Fact : FSet2) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001826 const FactEntry *LDat1 = nullptr;
1827 const FactEntry *LDat2 = &FactMan[Fact];
1828 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
1829 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001830
DeLesley Hutchins42665222014-08-04 16:10:59 +00001831 if (LDat1) {
1832 if (LDat1->kind() != LDat2->kind()) {
1833 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
1834 LDat2->loc(), LDat1->loc());
1835 if (Modify && LDat1->kind() != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001836 // Take the exclusive lock, which is the one in FSet2.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001837 *Iter1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001838 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001839 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001840 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001841 // The non-asserted lock in FSet2 is the one we want to track.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001842 *Iter1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001843 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001844 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001845 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
1846 Handler);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001847 }
1848 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001849
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001850 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00001851 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001852 const FactEntry *LDat1 = &FactMan[Fact];
1853 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001854
DeLesley Hutchins42665222014-08-04 16:10:59 +00001855 if (!LDat2) {
Ed Schoutenca988742014-09-03 06:00:11 +00001856 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
1857 Handler);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001858 if (Modify)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001859 FSet1.removeLock(FactMan, *LDat1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001860 }
1861 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001862}
1863
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001864
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00001865// Return true if block B never continues to its successors.
1866inline bool neverReturns(const CFGBlock* B) {
1867 if (B->hasNoReturnElement())
1868 return true;
1869 if (B->empty())
1870 return false;
1871
1872 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00001873 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
1874 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00001875 return true;
1876 }
1877 return false;
1878}
1879
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001880
Caitlin Sadowski33208342011-09-09 16:11:56 +00001881/// \brief Check a function's CFG for thread-safety violations.
1882///
1883/// We traverse the blocks in the CFG, compute the set of mutexes that are held
1884/// at the end of each block, and issue warnings for thread safety violations.
1885/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00001886void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001887 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
1888 // For now, we just use the walker to set things up.
1889 threadSafety::CFGWalker walker;
1890 if (!walker.init(AC))
1891 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001892
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001893 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001894 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001895
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001896 CFG *CFGraph = walker.getGraph();
1897 const NamedDecl *D = walker.getDecl();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001898 const FunctionDecl *CurrentFunction = dyn_cast<FunctionDecl>(D);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001899 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001900
Aaron Ballman9ead1242013-12-19 02:39:40 +00001901 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001902 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001903
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00001904 // FIXME: Do something a bit more intelligent inside constructor and
1905 // destructor code. Constructors and destructors must assume unique access
1906 // to 'this', so checks on member variable access is disabled, but we should
1907 // still enable checks on other objects.
1908 if (isa<CXXConstructorDecl>(D))
1909 return; // Don't check inside constructors.
1910 if (isa<CXXDestructorDecl>(D))
1911 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001912
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001913 Handler.enterFunction(CurrentFunction);
1914
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001915 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001916 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001917
1918 // We need to explore the CFG via a "topological" ordering.
1919 // That way, we will be guaranteed to have information about required
1920 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001921 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00001922 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001923
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00001924 // Mark entry block as reachable
1925 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
1926
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001927 // Compute SSA names for local variables
1928 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
1929
Richard Smith92286672012-02-03 04:45:26 +00001930 // Fill in source locations for all CFGBlocks.
1931 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
1932
DeLesley Hutchins42665222014-08-04 16:10:59 +00001933 CapExprSet ExclusiveLocksAcquired;
1934 CapExprSet SharedLocksAcquired;
1935 CapExprSet LocksReleased;
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001936
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00001937 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00001938 // to initial lockset. Also turn off checking for lock and unlock functions.
1939 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00001940 if (!SortedGraph->empty() && D->hasAttrs()) {
1941 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001942 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001943 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001944
DeLesley Hutchins42665222014-08-04 16:10:59 +00001945 CapExprSet ExclusiveLocksToAdd;
1946 CapExprSet SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00001947 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001948
1949 SourceLocation Loc = D->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00001950 for (const auto *Attr : ArgAttrs) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001951 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00001952 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001953 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00001954 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00001955 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00001956 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001957 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
1958 // We must ignore such methods.
1959 if (A->args_size() == 0)
1960 return;
1961 // FIXME -- deal with exclusive vs. shared unlock functions?
Aaron Ballman0491afa2014-04-18 13:13:15 +00001962 getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
1963 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00001964 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00001965 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001966 if (A->args_size() == 0)
1967 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001968 getMutexIDs(A->isShared() ? SharedLocksAcquired
1969 : ExclusiveLocksAcquired,
1970 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00001971 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00001972 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
1973 // Don't try to check trylock functions for now
1974 return;
1975 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
1976 // Don't try to check trylock functions for now
1977 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001978 }
1979 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001980
1981 // FIXME -- Loc can be wrong here.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001982 for (const auto &Mu : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001983 addLock(InitialLockset,
1984 llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc),
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001985 CapDiagKind, true);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001986 for (const auto &Mu : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001987 addLock(InitialLockset,
1988 llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc),
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001989 CapDiagKind, true);
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001990 }
1991
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001992 for (const auto *CurrBlock : *SortedGraph) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001993 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001994 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00001995
1996 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001997 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001998
1999 // Iterate through the predecessor blocks and warn if the lockset for all
2000 // predecessors is not the same. We take the entry lockset of the current
2001 // block to be the intersection of all previous locksets.
2002 // FIXME: By keeping the intersection, we may output more errors in future
2003 // for a lock which is not in the intersection, but was in the union. We
2004 // may want to also keep the union in future. As an example, let's say
2005 // the intersection contains Mutex L, and the union contains L and M.
2006 // Later we unlock M. At this point, we would output an error because we
2007 // never locked M; although the real error is probably that we forgot to
2008 // lock M on all code paths. Conversely, let's say that later we lock M.
2009 // In this case, we should compare against the intersection instead of the
2010 // union because the real error is probably that we forgot to unlock M on
2011 // all code paths.
2012 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002013 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002014 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2015 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2016
2017 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002018 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002019 continue;
2020
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002021 int PrevBlockID = (*PI)->getBlockID();
2022 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2023
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002024 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002025 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002026 continue;
2027
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002028 // Okay, we can reach this block from the entry.
2029 CurrBlockInfo->Reachable = true;
2030
Richard Smith815b29d2012-02-03 03:30:07 +00002031 // If the previous block ended in a 'continue' or 'break' statement, then
2032 // a difference in locksets is probably due to a bug in that block, rather
2033 // than in some other predecessor. In that case, keep the other
2034 // predecessor's lockset.
2035 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2036 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2037 SpecialBlocks.push_back(*PI);
2038 continue;
2039 }
2040 }
2041
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002042 FactSet PrevLockset;
2043 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002044
Caitlin Sadowski33208342011-09-09 16:11:56 +00002045 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002046 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002047 LocksetInitialized = true;
2048 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002049 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2050 CurrBlockInfo->EntryLoc,
2051 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002052 }
2053 }
2054
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002055 // Skip rest of block if it's not reachable.
2056 if (!CurrBlockInfo->Reachable)
2057 continue;
2058
Richard Smith815b29d2012-02-03 03:30:07 +00002059 // Process continue and break blocks. Assume that the lockset for the
2060 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002061 for (const auto *PrevBlock : SpecialBlocks) {
Richard Smith815b29d2012-02-03 03:30:07 +00002062 int PrevBlockID = PrevBlock->getBlockID();
2063 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2064
2065 if (!LocksetInitialized) {
2066 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2067 LocksetInitialized = true;
2068 } else {
2069 // Determine whether this edge is a loop terminator for diagnostic
2070 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2071 // it might also be part of a switch. Also, a subsequent destructor
2072 // might add to the lockset, in which case the real issue might be a
2073 // double lock on the other path.
2074 const Stmt *Terminator = PrevBlock->getTerminator();
2075 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2076
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002077 FactSet PrevLockset;
2078 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2079 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002080
Richard Smith815b29d2012-02-03 03:30:07 +00002081 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002082 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2083 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002084 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002085 : LEK_LockedSomePredecessors,
2086 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002087 }
2088 }
2089
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002090 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2091
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002092 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002093 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2094 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002095 switch (BI->getKind()) {
2096 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002097 CFGStmt CS = BI->castAs<CFGStmt>();
2098 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002099 break;
2100 }
2101 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2102 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002103 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2104 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2105 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002106 if (!DD->hasAttrs())
2107 break;
2108
2109 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002110 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
John McCall113bee02012-03-10 09:33:50 +00002111 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002112 AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002113 LocksetBuilder.handleCall(&DRE, DD);
2114 break;
2115 }
2116 default:
2117 break;
2118 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002119 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002120 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002121
2122 // For every back edge from CurrBlock (the end of the loop) to another block
2123 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2124 // the one held at the beginning of FirstLoopBlock. We can look up the
2125 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2126 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2127 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2128
2129 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002130 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002131 continue;
2132
2133 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002134 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2135 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2136 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2137 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002138 LEK_LockedSomeLoopIterations,
2139 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002140 }
2141 }
2142
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002143 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2144 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002145
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002146 // Skip the final check if the exit block is unreachable.
2147 if (!Final->Reachable)
2148 return;
2149
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002150 // By default, we expect all locks held on entry to be held on exit.
2151 FactSet ExpectedExitSet = Initial->EntrySet;
2152
2153 // Adjust the expected exit set by adding or removing locks, as declared
2154 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2155 // issue the appropriate warning.
2156 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002157 for (const auto &Lock : ExclusiveLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002158 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2159 Lock, LK_Exclusive, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002160 for (const auto &Lock : SharedLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002161 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2162 Lock, LK_Shared, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002163 for (const auto &Lock : LocksReleased)
2164 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002165
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002166 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002167 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002168 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002169 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002170 LEK_NotLockedAtEndOfFunction,
2171 false);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002172
2173 Handler.leaveFunction(CurrentFunction);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002174}
2175
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002176
2177/// \brief Check a function's CFG for thread-safety violations.
2178///
2179/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2180/// at the end of each block, and issue warnings for thread safety violations.
2181/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002182void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002183 ThreadSafetyHandler &Handler) {
2184 ThreadSafetyAnalyzer Analyzer(Handler);
2185 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002186}
2187
2188/// \brief Helper function that returns a LockKind required for the given level
2189/// of access.
2190LockKind getLockKindFromAccessKind(AccessKind AK) {
2191 switch (AK) {
2192 case AK_Read :
2193 return LK_Shared;
2194 case AK_Written :
2195 return LK_Exclusive;
2196 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002197 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002198}
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002199
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002200}} // end namespace clang::threadSafety